Cross domain Ajax request from within js file

后端 未结 7 1931
清酒与你
清酒与你 2020-11-30 10:17

Here\'s the problem:

1.) We have page here... www.blah.com/mypage.html

2.) That page requests a js file www.foo.com like this...



        
相关标签:
7条回答
  • 2020-11-30 10:56

    As mentioned above JSONP is a way around this. However, the site that you are requesting the data from needs to support JSONP in order for you to use on the client. (JSONP essentially injects a script tag into the page, and provides a callback function that should be called with the results)

    If the site you are making a request to does not support JSONP you will have to proxy the request on your server. As mentioned above you can do this on your own server or what I have done in the past is use a http://www.jsonpit.com, which will proxy the request for you.

    0 讨论(0)
  • 2020-11-30 11:01

    JSONP was partially designed to get around the problem you are having

    http://ajaxian.com/archives/jsonp-json-with-padding

    JQuery has it in their $.getJSON method

    http://docs.jquery.com/Ajax/jQuery.getJSON

    0 讨论(0)
  • 2020-11-30 11:02

    For cross domain hits this is a good working example and now is considered as some what "standard" http://www.xml.com/pub/a/2005/12/21/json-dynamic-script-tag.html.

    there are other ways as well, for eg injecting iframes with document.domain altered

    http://fettig.net/weblog/2005/11/28/how-to-make-xmlhttprequest-connections-to-another-server-in-your-domain/

    I still agre that the easy way is calling a proxy in same domain but then it's not truly client side WS call.

    0 讨论(0)
  • 2020-11-30 11:03

    It is XSS and it is forbidden. You should really not do things that way.

    If you really need to, make your AJAX code call the local code (PHP, ASP, whatever) on blah.com and make it behave like client and fetch whatever you need from foo.com and return that back to the client. If you use PHP, you can do this with fopen('www.foo.com/blah.html', 'r') and then reading the contents as if it was a regular file.

    Of course, allow_remote_url_fopen (or whatever it is called exactly) needs to be enabled in your php.ini.

    0 讨论(0)
  • 2020-11-30 11:08

    The method shown above could become a large security hole. Suggest you verify the site name against a white list and build the actual URI being proxied on the server side.

    0 讨论(0)
  • 2020-11-30 11:10

    There is a w3c proposal for allowing sites to specify other sites which are allowed to make cross site queries to them. (Wikipedia might want to allow all request for articles, say, but google mail wouldn't want to allow requests - since this might allow any website open when you are logged into google mail to read your mail).

    This might be available at some point in the future.

    0 讨论(0)
提交回复
热议问题