Angularjs。 JSONP。发送数据数据、Angularjs、JSONP

2023-09-13 04:09:50 作者:人心太凉、别太善良

我尝试使用AngularJS JSONP请求发送数据。

I try to send data using JSONP request in AngularJS.

$http({ method: 'jsonp', 
url: 'http://test.local/?callback=JSON_CALLBACK',  /// Add '?callback=JSON_CALLBACK'
data: JSON.stringify(request) })
.success(function (data, status, headers, config) { });

这可能吗?

推荐答案

是有可能看到的 $ HTTP。 JSONP功能。总之,你应该做这样的事情。

Yes it's possible see the $http.jsonp function. In short you should do something like

$http.jsonp('http://www.example.com?callback=JSON_CALLBACK')
  .success (function(data, ...) {
    //your data here
    ...
  })

请注意,您必须将回调= JSON_CALLBACK 作为你的HTTP调用的查询参数,以便角度做它的魔力。

Please be aware that you must set callback=JSON_CALLBACK as a query parameter of your http call in order for angular to do its magic.

要与你的请求一起发送数据,如果你想查询参数(1)这将取决于,请求消息数据(2)或两者(3)。

To send data along with your request it will depend if you want query parameters (1), request message data (2) or both (3).

案例1:

$http.jsonp('http://www.example.com?callback=JSON_CALLBACK', {params : Object | String})

按文档字符串或对象的地图将被转向键1 =值&放大器;。键2 =值的网址后,如果该值不是一个字符串,它会被JSONified

as per documentation "Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified."

案例2:

$http.jsonp('http://www.example.com?callback=JSON_CALLBACK', {data : Object | String})

案例3:

$http.jsonp('http://www.example.com?callback=JSON_CALLBACK', {params : Object | String, data : Object | String})