正确使用JSONP

时间:2016-04-29 07:57:22

标签: javascript jsonp

要成功使用JSONP(例如通过jquery - $ .ajax ......等),必须始终将所请求的页面设计为提供与此格式相对应的数据吗?

换句话说,如果我对具有纯静态内容的页面(即没有php,aspx等)执行请求,我也会收到错误吗?

这个问题对某些用户来说似乎微不足道,但我现在就开始学习这些技术,事情有点复杂。

基于这些(ref1 ref2)引用,似乎请求与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

1 个答案:

答案 0 :(得分:1)

  

要成功使用JSONP(例如通过jquery - $ .ajax ...等)必须始终如一,请求的页面是否设计为提供与此格式相对应的数据?

是。只有在响应表示为JSONP时,对JSONP的请求才有效。

  

换句话说,如果我对具有纯静态内容的页面执行请求(即没有php,aspx等),我也会收到错误吗?

您可以拥有符合JSONP格式的静态JavaScript程序(它需要对回调函数名称进行硬编码),因此不一定如此。

相关问题