0

我正在创建一个简单的 JSON API,它使用 jsonp 使用 node-js 返回我一个对象这是服务器端的代码:

app.get('/vit',function  (req,res,next) {
    res.type('application/json');
    res.jsonp(items);  //items is the object
});

在部署到 nodejitsu 并转到 url /vit 我得到对象项目。这意味着它在服务器端工作。

我有另一个域,我想从其中使用 jsonp 获取此对象继承客户端代码:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $.getJSON('http://trial.jit.su/vit',function  (data) {
       console.log(data) ;
    });
</script>

但我在控制台上收到以下错误:

XMLHttpRequest cannot load http://trial.jit.su/vit. Origin http://jquer.in is not allowed by Access-Control-Allow-Origin.

好像我还没有理解Jsonp。

4

1 回答 1

6

Quoting the jQuery docs

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

http://api.jquery.com/jQuery.getJSON/

You need a query string param with a question mark as placeholder.

And looking at the response of http://trial.jit.su/vit you're missing the callback function. You're just returning plain JSON without the P, e.g. if the url contains ?callback=bacon your response needs to be

bacon({"your": "json string"});

But express will do this for you, as long as you supply a callback param.

So just change the following:

$.getJSON('http://trial.jit.su/vit?callback=?',function  (data) {
    console.log(data) ;
});
于 2012-12-18T07:54:11.770 回答