跨域jsonp的基本操作方法 [英] Basic how-to for cross domain jsonp

查看:92
本文介绍了跨域jsonp的基本操作方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处都是这里。我需要一个简单的how-to拉jsonp交叉域。我使用的是jQuery 1.5.1。



我在另一个网站的程序中尝试过下面的代码:

  $。getJSON(http://www.mydomain.com/testjson.json?jsoncallback=?,function(data){
alert(I'm hitting this 。);
}

这根本不起作用。



有没有办法做一个简单的跨域jquery JSONP调用?



感谢


你不能使用JSONP拉取随机页面并期望它们成功;服务器需要知道:

JSONP需要服务器的协作才能成功,


  1. 它需要制定JSONP响应,而不是JSON响应。

  2. 需要知道


  3. 如果您不确定为什么服务器需要知道这些,或者区别是什么在JSON和JSONP之间,你应该读一下它们;或者整个事情都没有意义。对于初学者,请查看可以任何一个解释我是什么是JSONP的外行人条款 http://en.wikipedia.org/wiki/JSONP



    了解这一点后,您可能会发现服务器正在返回

      {key:1,bar:foo} 

    (这是有效的JSON),而不是:

      someCallback({key:1,bar: foo})

    这是一个JSONP响应。


    I looked everywhere here for this. I need just a simple "how-to" pull jsonp cross domain. I'm using jQuery 1.5.1.

    I tried the following in a program on another site:

    $.getJSON("http://www.mydomain.com/testjson.json?jsoncallback=?", function(data) {
        alert("I'm hitting this.");
    }
    

    This doesn't work at all.

    Is there a way of just doing a simple cross domain jquery JSONP call?

    Thanks

    解决方案

    JSONP requires the cooperation of the server to succeed. You cannot pull random pages using JSONP and expect them to succeed; the server needs to know:

    1. It needs to formulate a JSONP response, rather than a JSON response.
    2. It needs to know the name of the function to wrap the response around.

    If you're unsure on why the server needs to know these, or what the differences are between JSON and JSONP, you should read up on them; or the whole thing will make no sense. For starters, check out can any one explain me what is JSONP in layman terms and http://en.wikipedia.org/wiki/JSONP.

    After understanding this a little more, you'll probably find the server is returning

    { "key": 1, "bar": "foo" }
    

    (which is valid JSON), rather than:

    someCallback({ "key": 1, "bar": "foo" })
    

    which is a JSONP response.

    这篇关于跨域jsonp的基本操作方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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