$ .getJSON获取JSONP数据 [英] $.getJSON to get JSONP data

查看:431
本文介绍了$ .getJSON获取JSONP数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过以下方式使用$ .getJSON来接收警报,但没有运气.

这是代码,

<script type="text/javascript">
    $(document).ready(function() {
        var url = "ticker.js?callback=?";
        $.getJSON(url, function(data) {
            alert(data.price);
        });

    });
</script>

ticker.js文件只有以下一行

{ticket:'IBM',price:14.57}

应该收到警报"14.57",但我没有收到警报.

如果您希望看到它的实际效果,可以尝试使用该链接, http://nazmulweb.com/site5/demo/jsonPtest/

解决方案

如果它是本地文件,则应删除?callback=?部分,如下所示:

var url = "ticker.js";
$.getJSON(url, function(data) {
   alert(data.price);
});

如果您查看 $.getJSON()文档,就会发现:

如果URL包含字符串"callback=?",则该请求将被视为JSONP.有关更多详细信息,请参见 $ .ajax()中对jsonp数据类型的讨论.

使用JSONP时,期望的响应是randomFunctioName({ticket:'IBM',price:14.57});,而不是JSON的 ,而是一个函数调用...这就是JSONP通过成为<script>标签跨域工作的方式.由于您只想使用JSON并从 local 来源处理它,因此请删除callback=?片段.

我完全错过了第二个问题,您当前的JSON无效,并且将无法通过1.4中添加的jQuery检查.必须是这样的:

{ "ticket": "IBM", "price": 14.57 }

您可以在此处测试JSON的有效性: http://www.jsonlint.com/

I was playing with $.getJSON in the following way to receive an alert but without luck.

Here is the code,

<script type="text/javascript">
    $(document).ready(function() {
        var url = "ticker.js?callback=?";
        $.getJSON(url, function(data) {
            alert(data.price);
        });

    });
</script>

And the ticker.js file has only the following line

{ticket:'IBM',price:14.57}

It is supposed to get an alert "14.57" but I am not getting the alert.

If you would like to see it in action you may try the link, http://nazmulweb.com/site5/demo/jsonPtest/

解决方案

If it's a local file, you should remove the ?callback=? part, like this:

var url = "ticker.js";
$.getJSON(url, function(data) {
   alert(data.price);
});

If you look at the $.getJSON() docs, there's this:

If the URL includes the string "callback=?" in the URL, the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

With JSONP it's expecting randomFunctioName({ticket:'IBM',price:14.57}); in the response, not just the JSON, but a function call...this is how JSONP works cross-domain, by being a <script> tag. Since you just want JSON and to process it from a local source, remove the callback=? piece.

Edit: I completely missed the second issue, your current JSON isn't valid and will fail jQuery's checks added in 1.4. It needs to be this:

{ "ticket": "IBM", "price": 14.57 }

You can test your JSON for validity here: http://www.jsonlint.com/

这篇关于$ .getJSON获取JSONP数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆