简体   繁体   中英

Unable to get data from web service while using JSONP

I am trying to make a web service call using JSONP. When I called the service using JSON it worked fine. Here is the code for JSON:

$.ajax({
                type:defaultOpt.type,
                contentType: "application/json; charset=utf-8",
                dataType: defaultOpt.dataType,
                url: defaultOpt.url,
                data: defaultOpt.data,
                success: defaultOpt.successCallback,
                error: defaultOpt.errorCallback,
                async: defaultOpt.asyn
});

However when I call the same service using JSONP, I don't get anything in the response. Here is the code for the call using JSONP:

$.ajax({
                    dataType: 'jsonp',
                    data: defaultOpt.data,
                    url: defaultOpt.url,
                    success: function (data) {
                        alert('Success');
                    },
                    error: function (data) {
                        alert("Error");
                    }
 });

This is the stringified response that I get when I use JSONP.

{"readyState":4,"status":200,"statusText":"success"}

It shows success but I don't get the response data from web service.

Chances are your server doesn't support JSONP. Yet. If you control the server, you can add this support yourself.

The idea of JSONP is that the browser loads and executes it as javascript, rather than as Ajax data. So to pass data, the response needs to call a callback function and pass the data as a parameter. The response might look like this:

callback({"readyState":4,"status":200,"statusText":"success"});

Your website needs to have that callback function specified of course, but I think JQuery generates this for you automatically, and has this callback call your success function. I'm not entirely sure about that, so check the docs. And of course the server has to listen to the callback parameter so it uses that name for the function call it wraps your data in.

As you can probably tell, JSONP is a really ugly hack. There's a nicer solution for cross-domain calls that's supported by all modern browsers, which is to add an Accept-Control-Allow-Origin header to the server's response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM