要成功使用JSONP(例如,通过jquery - $ .ajax等),必须始终确保所请求的页面旨在提供与此格式相对应的数据?换句话说,如果我对纯静态内容(即没有php,aspx等)的页面执行请求,我也会得到一个错误吗?正确使用JSONP
对于某些用户来说,这个问题可能看起来微不足道,但我现在开始学习这些技术,事情有点复杂。
基于这些(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
EDIT2
$.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通过利用脚本可以跨不同来源加载的事实来解决同源策略。为了使黑客行得通,服务器和客户端之间必须有协议。 –
'crossDomain:true,'停止jQuery将标题添加到XHR,它只会为相同的原始请求添加标头(如果同一个来源将HTTP重定向到不同的来源)。对于一个开始是跨源的请求并没有对JSONP请求产生任何影响是没有意义的(因为没有办法控制头文件) – Quentin
'dataCharset'不是jQuery ajax设置对象接受的属性 – Quentin