AngularJS http.jsonp 请求 .then 和 .success 函数不起作用

AngularJS http.jsonp request .then and .success functions not work

我的客户端应用程序是一个 angularJS 应用程序。服务器由Laravel 5.

搭建

在客户端中,我进行了一个 jsonp CORS 请求:

$http.jsonp("http://server.com/api?callback=JSON_CALLBACK")

在laravel服务器中,返回一个json数据:

return Response()->json($query);

然而,当我尝试

$http.jsonp("http://server.com/api?callback=JSON_CALLBACK")
.then(function(response){
    alert('success');
});

$http.jsonp("http://server.com/api?callback=JSON_CALLBACK")
.success(function(response){
    alert('success');
});

两个状态都是200 OK。但是不会出现任何警报。我尝试

$http.jsonp("http://server.com/api?callback=JSON_CALLBACK")
.then(function(response){
    alert('success');
},function(error){
    alert('fail');
});

结果是 200 OK 的状态,但警报是“失败”!我怎么解决这个问题?谢谢!

JSONP 需要服务器端的回调函数 "JSON_CALLBACK"。或者,您可以使用代理。 http://www.whateverorigin.org/

Angular的$http.jsonp将请求querystring参数从callback=JSON_CALLBACK转换为callback=angular.callbacks._0.

在 Laravel 的控制器中,您需要将前缀添加到您的响应字符串中。

return $request->input('callback')."(".$query.")";

然后,angular 应用程序将确认此响应并传递给 .then.success 函数。