问题描述
我正在学习 AngularJS 并尝试构建从 Wordpress 获取数据的前端系统.
I'm learning AngularJS and trying to build front-end system that gets data from Wordpress.
在后端,一切似乎都设置正确,当我使用 jQuery ajax 请求时,它可以毫无问题地获取数据.
On the back-end side everything seems to be set up properly and when I use jQuery ajax request it gets the data without problems.
jQuery.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'getdataajax'
},
success: function(data, textStatus, XMLHttpRequest){
console.log(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
console.log(errorThrown);
}
});
但是当我尝试用 AngularJS 做同样的事情时,它不起作用.我正在尝试使用如下代码复制 ajax 请求:
But when I try to do the same thing with AngularJS, it does not work. I'm trying to replicate the ajax request with code like this:
myApp.factory('productsData', function($http, $log) {
return {
getProducts: function(successcb) {
return $http({
method: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {action: 'getdataajax'}
}).success(function(data, status, headers, config) {
successcb(data);
$log.info(data, status, headers(), config)
}).error(function(data, status, headers, config) {
$log.warn(data, status, headers(), config)
});
},
};
});
如果我记录它,它会输出 0.我错过了什么?
If I log it, it outputs 0. What am I missing?
感谢您的帮助.
附言控制器看起来像这样:
P.S. Controller looks like this:
myApp.controller('ProductsController', function ProductsController($scope, productsData) {
$scope.sortorder = 'name';
// $scope.products = productsData.products;
// $scope.products = productsData.getProducts();
productsData.getProducts(function(products){
$scope.products = products;
});
});
推荐答案
在 angularjs 代码中,使用 params:
而不是 data:
.
In the angularjs code, use params:
instead of data:
.
在 jquery 中,提供给 data:
配置设置的对象将转换为查询字符串 (?key1=val1&key2=value2),除非您设置 processData: false
.在 angularjs 中,您必须使用 params:
来获取查询字符串,data:
作为 json 或字符串发送.
In jquery the object supplied to the data:
config setting is converted to a query string (?key1=val1&key2=value2) unless you set processData: false
. in angularjs, you have to use params:
to get a query string, data:
is sent as json or string.
这篇关于jQuery ajax 请求有效,同样的 AngularJS ajax 请求无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!