Javascript 未使用 JSONP 触发 Jquery 成功函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2380551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery success function not firing using JSONP
提问by Sanjay Uttam
Been doing some playing call my service which is on a different domain using jQuery. The call to the service is successfully made (my debug point gets tripped), and the correct response is returned (I sniff the traffic).
一直在使用 jQuery 调用我在不同域上的服务。对服务的调用成功(我的调试点被触发),并返回正确的响应(我嗅探流量)。
My problem is mainly that the success and failure callbacks don't get fired. I have read some other postson SO that indicate the error event is not fired when using JSONP. Is that the case with the success event (perhaps because it is assumed that I am providing my own callback function), as well, or is there a way to fire my success callback. Thanks in advance.
我的问题主要是成功和失败回调不会被触发。我已经阅读了其他一些关于 SO 的帖子,这些帖子表明使用 JSONP 时不会触发错误事件。成功事件是否也是这种情况(可能是因为假设我正在提供我自己的回调函数),或者有没有办法触发我的成功回调。提前致谢。
$.ajax({
type: "GET",
url: urlOnDiffDomain,
async: false,
cache: false,
dataType: 'jsonp',
data: {},
success: function(data, textStatus) {
alert('success...');
},
error: function(xhr, ajaxOptions, thrownError) {
alert('failed....');
}
});
采纳答案by Sanjay Uttam
Alright. In case anyone needs to know in the future...In hindsight, the solution probably should have been more obvious than it was, but you need to have the web-response write directly to the response stream. Simply returning a string of JSON doesn't do it, you need to someone construct it and stream it back. The code in my original post will work fine if you do indeed do that.
好吧。如果将来有人需要知道......事后看来,解决方案可能应该比以前更明显,但您需要将网络响应直接写入响应流。简单地返回一串 JSON 并不能做到这一点,您需要有人构造它并将其流式传输回来。如果您确实这样做,我原帖中的代码将正常工作。
Example of service code:
服务代码示例:
public void DoWork()
{
//it will work without this, but just to be safe
HttpContext.Current.Response.ContentType = "application/json";
string qs = HttpContext.Current.Request.QueryString["callback"];
HttpContext.Current.Response.Write(qs + "( [{ \"x\": 10, \"y\": 15}] )");
}
Just for the sake of being explicit, this is the client-side code.
只是为了明确起见,这是客户端代码。
function localDemo(){
$.getJSON("http://someOtherDomain.com/Service1.svc/DoWork?callback=?",
function(data){
$.each(data, function(i,item){
alert(item.x);
});
});
}
If there is a better way to do this, I am all ears. For everyone else, I know there is some concept of native support in WCF 4.0 for JSONP. Also, you may want to do a little checkingfor security purposes - though I have not investigated much.
如果有更好的方法来做到这一点,我全神贯注。对于其他所有人,我知道 WCF 4.0 中有一些对 JSONP 的本机支持的概念。此外,出于安全目的,您可能需要进行一些检查- 尽管我没有进行太多调查。
回答by Guffa
The successcallback method is called when the server responds. The $.ajaxmethod sets up a function that handles the response by calling the successcallback method.
在success当服务器响应回调方法被调用。该$.ajax方法设置了一个函数,通过调用success回调方法来处理响应。
The most likely reason that the successmethod is not called, is that the response from the server is not correct. The $.ajaxmethod sends a value in the callbackquery string that the server should use as function name in the JSONP response. If the server is using a different name, the function that the $.ajaxmethod has set up is never called.
success未调用该方法的最可能原因是来自服务器的响应不正确。该$.ajax方法在callback查询字符串中发送一个值,服务器应将其用作 JSONP 响应中的函数名称。如果服务器使用不同的名称,$.ajax则永远不会调用该方法设置的函数。
If the server can not use the value in the callbackquery string to set the function name in the response, you can specify what function name the $.ajaxmethod should expect from the server. Add the property jsonpCallbackto the option object, and set the value to the name of the function that the server uses in the response.
如果服务器无法使用callback查询字符串中的值来设置响应中的函数名称,您可以指定该$.ajax方法应该从服务器获得的函数名称。将属性添加jsonpCallback到选项对象,并将值设置为服务器在响应中使用的函数的名称。
If for example the $.ajaxmethod is sending a request to the server using the URL http://service.mydomain.com/getdata?callback=jsonp12345, the server should respond with something looking like:
例如,如果该$.ajax方法使用 URLhttp://service.mydomain.com/getdata?callback=jsonp12345向服务器发送请求,则服务器应以如下方式响应:
jsonp12345({...});
If the server ignores the callbackquery string, and instead responds with something like:
如果服务器忽略callback查询字符串,而是响应如下:
mycallback({...});
Then you will have to override the function name by adding a property to the options object:
然后,您必须通过向选项对象添加属性来覆盖函数名称:
$.ajax({
url: urlOnDiffDomain,
dataType: 'jsonp',
data: {},
success: function(data, textStatus) {
alert('success...');
},
jsonpCallback: 'mycallback'
});
回答by Learner
This is not a complete answer to your question, but I think someone who passes by would like to know this:
这不是您问题的完整答案,但我认为路过的人想知道这一点:
When you deal with JSONP from WCF RESTtry to use:
当您从 WCF REST处理JSONP 时,请尝试使用:
[JavascriptCallbackBehavior(UrlParameterName = "$callback")]
[JavascriptCallbackBehavior(UrlParameterName = "$callback")]
for your service implementation; this should give you JSONP out-of-the-box.
为您的服务实施;这应该为您提供开箱即用的 JSONP。
回答by Darkhan
$.ajax({
url:' <?php echo URL::site('ajax/editing?action=artistSeracher') ?>',
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
artist: request.term
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.artist,
value: item.artist,
id: item.id
}
}));
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
回答by Darkhan
Try
尝试
$.getJSON(urlOnDiffDomain, function(data, textStatus){
alert('success...');
});
Works for me, usally. You need to add &callback=? to urlOnDiffDomain, where jQuery automatically replaces the callback used in JSONP.
通常对我有用。您需要添加 &callback=? 到 urlOnDiffDomain,其中 jQuery 自动替换 JSONP 中使用的回调。
The error callback is not triggered, but you can use the global $.ajaxError, like this
不触发错误回调,但是可以使用全局$.ajaxError,像这样
$('.somenode').ajaxError(function(e, xhr, settings, exception) {
alert('failed');
});

