所有
[更新] 我弄清楚了,结果是:
$http({
url: "http://localhost:3000/users",
method: "JSONP",
params: {
callback:"JSON_CALLBACK", // need to be this name
q: $scope.qs
}
})
.success(function( data ){
console.log("return data length:",data.length);
if(data.length>0){
$scope.cdata = data;
}
})
=============================================== =========== 我是ExpressJS和AngularJS的新手,现在,我正在尝试使用Express构建REST JSONP服务来提供数据。
当我在前端尝试Angular时:
$scope.qs = 0;
$http({
url: "http://localhost:3000/users",
method: "JSONP",
params: {
callback:"dataservice",
q: $scope.qs
}
})
.success(function(err, data){
console.log("return data length:",data.length);
if(data.length>0){
$scope.cdata = data;
}
})
.error(function(data, err){
console.log(data, err);
});
};
我在服务器端使用:
/* GET users listing. */
router.get('/', function(req, res) {
var jsonp = req.query.callback;
var start = parseInt(req.query.q);
var retdata = [];
if( !isNaN(start) ){
retdata = cdata.slice(start);
}
if(jsonp){
console.log("I return as JSONP");
res.jsonp( retdata );
}else {
console.log("I return as JSON");
res.json( retdata );
}
});
从chrome控制台,我可以看到返回的JSONP响应如下:
/**/ typeof dataservice === 'function' && dataservice([{"Name":"Island Trading","City":"Cowes","Country":"UK"},{"Name":"Königlich Essen","City":"Brandenburg","Country":"Germany"},{"Name":"Laughing Bacchus Wine Cellars","City":"Vancouver","Country":"Canada"},{"Name":"Magazzini Alimentari Riuniti","City":"Bergamo","Country":"Italy"},{"Name":"North/South","City":"London","Country":"UK"},{"Name":"Paris spécialités","City":"Paris","Country":"France"},{"Name":"Rattlesnake Canyon Grocery","City":"Albuquerque","Country":"USA"},{"Name":"Simons bistro","City":"København","Country":"Denmark"},{"Name":"The Big Cheese","City":"Portland","Country":"USA"},{"Name":"Vaffeljernet","City":"Århus","Country":"Denmark"},{"Name":"Wolski Zajazd","City":"Warszawa","Country":"Poland"}]);
但Angular不能在.successs中使用它,但会触发.error处理程序。
我想知道是否有人可以帮我这个?如何使用返回响应
由于
答案 0 :(得分:0)
尝试这样做,您将发送回调,这是您必须调用以检索数据的内容:
function userCallback(data) {
console.log("return data length:",data.length);
if(data.length>0){
$scope.cdata = data;
}
}
$http({
url: "http://localhost:3000/users",
method: "JSONP",
params: {
callback: userCallback,
q: $scope.qs
}
}).then(userCallback);