Make cross-domain ajax JSONP request with jQuery

前端 未结 7 2149
鱼传尺愫
鱼传尺愫 2020-11-22 04:10

I would like to parse JSON array data with jquery ajax with the following code:



        
7条回答
  •  忘掉有多难
    2020-11-22 04:49

    Concept explained

    Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? 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);
    }
    

    Summary

    Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.

    If you have reqested with query string

    ?callback=my_callback_method
    

    then, your server must response data wrapped like this:

    my_callback_method({your json serialized data});
    

提交回复
热议问题