简体   繁体   English

使用JSONP时无法从Web服务获取数据

[英]Unable to get data from web service while using JSONP

I am trying to make a web service call using JSONP. 我正在尝试使用JSONP进行Web服务调用。 When I called the service using JSON it worked fine. 当我使用JSON调用服务时,它运行良好。 Here is the code for JSON: 这是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. 但是,当我使用JSONP调用同一服务时,响应中没有任何信息。 Here is the code for the call using JSONP: 这是使用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. 这是我使用JSONP时收到的字符串化响应。

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

It shows success but I don't get the response data from web service. 它显示成功,但是我没有从Web服务获得响应数据。

Chances are your server doesn't support JSONP. 您的服务器可能不支持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. JSONP的想法是浏览器以javascript而不是Ajax数据的形式加载并执行它。 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. 您的网站当然需要指定该回调函数,但是我认为JQuery会自动为您生成此函数,并让该回调函数调用您的成功函数。 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. 当然,服务器必须侦听callback参数,因此它将名称用于包装数据的函数调用。

As you can probably tell, JSONP is a really ugly hack. 您可能会说,JSONP是一个非常丑陋的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. 所有现代浏览器都支持一种更好的跨域调用解决方案,该解决方案是在服务器的响应中添加一个Accept-Control-Allow-Origin标头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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