-1

我试图在服务器中放置一个静态 jsonp 文件(jsonp-test.php),但我无法读取它。这就是我所拥有的:

mycallback[
  {"key":"1","val":"test1"},
  {"key":"2","val":"test2"}
]

这就是我试图阅读它的方式:

var url = "http://www.remote-server/jsonp-test.php?callback=mycallback";
$.getJSON(url, function(data) {
  alert(data.toSource());
});

我究竟做错了什么?

4

2 回答 2

0

First, as Bradley explained, fix the syntax of the JSONP file - it needs those parentheses. That's because the file needs to be valid JavaScript code. JSONP is just a convention for using a JavaScript function call to load JSON data from a script file.

If the file will remain static - in particular if the name of the mycallback function is hard coded - then you should probably just treat it as a script file that calls a global function, because that's what it really is. Define a global function named mycallback, and use $.getScript() to load your static JSONP/JavaScript file:

window.mycallback = function( data ) {
    alert( data.toSource() );
};

$.getScript( 'http://www.remote-server/jsonp-test.php' );

Note that you don't need the ?callback=mycallback for a static file either.

于 2013-09-23T02:52:33.437 回答
0

所以,有几件事......当你说“我无法阅读它”时,你能确认你实际上是从正确的地址请求 JSONP 吗?例如,你能打开网址吗?

http://www.remote-server/jsonp-test.php?callback=mycallback

在浏览器选项卡中查看 JSONP。如果是这样,那么我认为您的 JSONP 格式不正确的次要问题。mycallback 实际上是被调用的函数的名称,因此 JSON 的内容应该用半括号括在括号中,如下所示

mycallback(
  [
  {"key":"1","val":"test1"},
  {"key":"2","val":"test2"}
  ]
);
于 2013-09-23T02:07:29.393 回答