【发布时间】:2016-04-29 22:20:31
【问题描述】:
要成功使用 JSONP(例如通过 jquery - $.ajax ...等),必须始终要求所请求的页面旨在提供与此格式对应的数据?
换句话说,如果我对纯静态内容(即没有 php、aspx 等)的页面执行请求,我也会收到错误吗?
这个问题对某些用户来说可能看起来微不足道,但我现在开始学习这些技术,事情有点复杂。
基于这些 (ref1ref2) 引用,似乎 JSONP 的请求与服务器响应的实现之间必须保持一致。
编辑
我有这个 jQuery 请求
$.ajax({
url: "https://sites.google.com/site/problemsstore/javascript/test.js",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
我已经加载了https://sites.google.com/site/mysite/javascript/test.js?attredirects=0&d=1这个test.js文件:
function myCall(data) {
console.log('succeed');
}
myCall({ some : "data" });
当我连接时,我希望获得控制台的输出:succeed succeed。
这就是我得到的:
succeed
failed
编辑2
$.ajax({
url: "https://sites.google.com/site/bentofelicianolopez/jscript-jsonp/test.js?attredirects=0&d=1",
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
dataCharset: 'jsonp',
jsonp: 'myCall',
//contentType: 'application/json',
success: function (result) {
console.log('request succeed');
},
error: function (result) {
console.log('failed');
}
});
.js 文件:
myCall({ some : "data" });
输出:
failed test4.html:94:9
ReferenceError: myCall is not defined /*this is the syntactical error of which I said*/
test.js:1:1
【问题讨论】:
-
JSONP 是一种通过利用脚本可以跨不同来源加载的事实来绕过同源策略的黑客。要使 hack 起作用,服务器和客户端之间必须有协议。
-
crossDomain: true,阻止 jQuery 将标头添加到 XHR,它只为同源请求添加(以防同源将 HTTP 重定向到不同源)。对于开始是跨源并且对 JSONP 请求没有任何影响的请求是没有意义的(因为无法控制那里的标头) -
dataCharset不是 jQuery ajax 设置对象接受的属性
标签: javascript jsonp