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

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

本文关键字:success 函数 不起作用 then http jsonp 请求 AngularJS      更新时间:2024-05-15

我的客户端应用程序是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将请求查询字符串参数从callback=JSON_CALLBACK转换为callback=angular.callbacks._0

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

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

然后,角度应用程序将确认该响应并传递给.then.success功能。