Home >Web Front-end >JS Tutorial >How Can I Successfully Make Cross-Domain AJAX JSONP Requests with jQuery?

How Can I Successfully Make Cross-Domain AJAX JSONP Requests with jQuery?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-19 05:28:02302browse

How Can I Successfully Make Cross-Domain AJAX JSONP Requests with jQuery?

Making Cross-Domain AJAX JSONP Requests with jQuery

When attempting to parse JSON array data using jQuery ajax cross-domain, it's essential to note that the remote server hosting the data must support method injection for JSONP to function properly.

In your code, the following block initiates an AJAX request using dataType: 'jsonp':

$.ajax({
    type: "GET",
    url: "http://10.211.2.219:8080/SampleWebService/sample.do",
    dataType: "jsonp",
    success: function (xml) {
        alert(xml.data[0].city);
        result = xml.code;
        document.myform.result1.value = result;
    },
});

When jQuery executes this request, it appends ?callback={some_random_dynamically_generated_method} to the URL. This method, typically attached to the window object, acts as a proxy and looks something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    // Calls the success callback
    successCallback(actualJsonData);
}

While your client-side code appears correct, it's imperative to modify your server-side code to wrap your JSON data with the function name passed via the query string. For instance, if the request URL includes ?callback=my_callback_method, the server should respond with JSON data wrapped in the following structure:

my_callback_method({your json serialized data});

This ensures that the JSON data is successfully parsed and made available to your client-side code.

The above is the detailed content of How Can I Successfully Make Cross-Domain AJAX JSONP Requests with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn