2016-04-29 22 views
-1

要成功使用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 
+1

JSONP通过利用脚本可以跨不同来源加载的事实来解决同源策略。为了使黑客行得通,服务器和客户端之间必须有协议。 –

+0

'crossDomain:true,'停止jQuery将标题添加到XHR,它只会为相同的原始请求添加标头(如果同一个来源将HTTP重定向到不同的来源)。对于一个开始是跨源的请求并没有对JSONP请求产生任何影响是没有意义的(因为没有办法控制头文件) – Quentin

+0

'dataCharset'不是jQuery ajax设置对象接受的属性 – Quentin

回答

1

To successfully use JSONP (e.g. via jquery - $ .ajax ... etc.) must always be, that the requested page is designed to provide data corresponding to this format?

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

In other words, if I perform a request to a page with a pure static content (i.e. no php, aspx, and so on), also I will get an error?

你可以有一个符合JSONP格式的静态JavaScript程序(它需要硬编码的回调函数名),所以没有必要。

+0

所以它不可能使用这种方法来简单地检查网络连接的存在(使用任意域)?将总是返回错误的请求? – Bento

+0

关于答案的第二部分,你能否给我提供一个例子的参考? – Bento

+0

@Bento - Err。 *例子的内容。js *:'someCallbackName({“some:”data“})' – Quentin