How to make cross domain request

This question already has an answer here:

  • What is JSONP all about? [duplicate] 7 answers

  • You can make cross domain requests using the XMLHttpRequest object. This is done using something called "Cross Origin Resource Sharing". See: http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

    Very simply put, when the request is made to the server the server can respond with a Access-Control-Allow-Origin header which will either allow or deny the request. The browser needs to check this header and if it is allowed then it will continue with the request process. If not the browser will cancel the request.

    You can find some more information and a working example here: http://www.leggetter.co.uk/2010/03/12/making-cross-domain-javascript-requests-using-xmlhttprequest-or-xdomainrequest.html

    JSONP is an alternative solution, but you could argue it's a bit of a hack.


    Do a cross-domain AJAX call

    Your web-service must support method injection in order to do JSONP.

    Your code seems fine and it should work if your web services and your web application hosted in the same domain.

    When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

    For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

    This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

    window.some_random_dynamically_generated_method = function(actualJsonpData) {
        //here actually has reference to the success function mentioned with $.ajax
        //so it just calls the success method like this: 
        successCallback(actualJsonData);
    }
    

    Check the following for more information

    http://json-p.org/

    Make cross-domain ajax JSONP request with jQuery


    If you're willing to transmit some data and that you don't need to be secured (any public infos) you can use a CORS proxy, it's very easy, you'll not have to change anything in your code or in server side (especially of it's not your server like the Yahoo API or OpenWeather). I've used it to fetch JSON files with an XMLHttpRequest and it worked fine.

    链接地址: http://www.djcxy.com/p/8342.html

    上一篇: P&你如何发音?

    下一篇: 如何制作跨域请求