Angularjs. Jsonp. Sending data

余生颓废 提交于 2019-12-10 11:46:46

问题


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) { });

Is this possible?


回答1:


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
    ...
  })

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.

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

Case 1 :

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

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."

Case 2 :

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

Case 3 :

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



回答2:


Late answer, but: data only works for POST requests. However you can't make a POST request with JSONP -- the way it works is it inserts a <script> tag into your DOM with src set to the URL of the request; when your browser evaluates the script it will call the callback parameter (Angular basically replaces JSON_CALLBACK by a pointer to your success function).

TL;DR: the only way you can send stuff to the server using JSONP is using the params key in the config.



来源:https://stackoverflow.com/questions/18676085/angularjs-jsonp-sending-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!