最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angularjs. Jsonp. Sending data - Stack Overflow

programmeradmin3浏览0评论

I try to send data using JSONP request in AngularJS.

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

Is this possible?

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?

Share Improve this question edited Jul 1, 2015 at 23:58 JasonMArcher 15k22 gold badges59 silver badges53 bronze badges asked Sep 7, 2013 at 17:39 ExyTabExyTab 5573 gold badges7 silver badges14 bronze badges 1
  • in angularjs document they have provided the JSONP sample, that may helpful. docs.angularjs/api/ng.$http#methods_jsonp – Uttesh Kumar Commented Dec 21, 2013 at 3:48
Add a ment  | 

2 Answers 2

Reset to default 9

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

$http.jsonp('http://www.example.?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.?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.?callback=JSON_CALLBACK', {data : Object | String})

Case 3 :

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

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.

发布评论

评论列表(0)

  1. 暂无评论