javascript Angularjs。杰森 发送数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18676085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angularjs. Jsonp. Sending data
提问by ExyTab
I try to send data using JSONP request in AngularJS.
我尝试在 AngularJS 中使用 JSONP 请求发送数据。
$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?
这可能吗?
回答by Nicolas ABRIC
Yes it's possible see the $http.jsonp function. In short you should do something like
是的,可以看到$http.jsonp 函数。总之你应该做类似的事情
$http.jsonp('http://www.example.com?callback=JSON_CALLBACK')
.success (function(data, ...) {
//your data here
...
})
Please be aware that you must set callback=JSON_CALLBACKas a query parameter of your http call in order for angular to do its magic.
请注意,您必须将callback=JSON_CALLBACK设置为 http 调用的查询参数,以便 angular 发挥其魔力。
To send data along with your request it will depend if you want query parameters (1), request message data (2) or both (3).
要将数据与您的请求一起发送,这取决于您是需要查询参数 (1)、请求消息数据 (2) 还是两者 (3)。
Case 1 :
情况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."
根据文档“将在 url 之后转换为 ?key1=value1&key2=value2 的字符串或对象的映射。如果值不是字符串,它将被 JSONified。”
Case 2 :
案例2:
$http.jsonp('http://www.example.com?callback=JSON_CALLBACK', {data : Object | String})
Case 3 :
案例3:
$http.jsonp('http://www.example.com?callback=JSON_CALLBACK', {params : Object | String, data : Object | String})
回答by Manuel Ebert
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).
迟到的答案,但是:data
仅适用于POST
请求。但是,您不能POST
使用 JSONP 发出请求——它的工作方式是将<script>
标签插入到您的 DOM 中,并src
设置为请求的 URL;当您的浏览器评估脚本时,它将调用回调参数(Angular 基本上用JSON_CALLBACK
指向您的成功函数的指针替换)。
TL;DR: the only way you can send stuff to the server using JSONP is using the params
key in the config.
TL;DR:使用 JSONP 将内容发送到服务器的唯一方法是使用params
配置中的密钥。