Jquery 成功函数未使用 JSONP 触发

发布于 2024-08-24 01:01:37 字数 618 浏览 5 评论 0原文

一直在使用 jQuery 调用我的服务,该服务位于不同的域中。对服务的调用已成功进行(我的调试点被触发),并且返回了正确的响应(我嗅探了流量)。

我的问题主要是成功和失败回调不会被触发。我读过一些 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....');
  }
}); 

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).

My problem is mainly that the success and failure callbacks don't get fired. I have read some other posts on 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.

$.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....');
  }
}); 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

演多会厌 2024-08-31 01:01:37

好吧。万一将来有人需要知道......事后看来,解决方案可能应该比以前更明显,但您需要将网络响应直接写入响应流。简单地返回 JSON 字符串并不能做到这一点,您需要有人构造它并将其流式传输回来。如果你确实这样做的话,我原来的帖子中的代码将工作得很好。

服务代码示例:

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}] )");
}

为了明确起见,这是客户端代码。

function localDemo(){
  $.getJSON("http://someOtherDomain.com/Service1.svc/DoWork?callback=?",
    function(data){
      $.each(data, function(i,item){            
        alert(item.x);
      });
  });
}

如果有更好的方法来做到这一点,我洗耳恭听。对于其他人,我知道 WCF 4.0 中有一些对 JSONP 的本机支持的概念。另外,您可能需要做一些 检查 出于安全目的 - 尽管我没有调查太多。

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.

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 checking for security purposes - though I have not investigated much.

妞丶爷亲个 2024-08-31 01:01:37

当服务器响应时,会调用 success 回调方法。 $.ajax 方法设置一个函数,通过调用 success 回调方法来处理响应。

未调用 success 方法的最可能原因是服务器的响应不正确。 $.ajax 方法在 callback 查询字符串中发送一个值,服务器应将其用作 JSONP 响应中的函数名称。如果服务器使用不同的名称,则永远不会调用 $.ajax 方法设置的函数。

如果服务器无法使用 callback 查询字符串中的值来设置响应中的函数名称,您可以指定 $.ajax 方法应该使用什么函数名称服务器。将属性 jsonpCallback 添加到选项对象,并将值设置为服务器在响应中使用的函数的名称。

例如,如果 $.ajax 方法使用 URL http://service.mydomain.com/getdata?callback=jsonp12345 向服务器发送请求,则服务器应该以如下形式响应:

jsonp12345({...});

如果服务器忽略回调查询字符串,而是以如下形式响应:

mycallback({...});

那么您必须通过向选项对象添加属性来覆盖函数名称:

$.ajax({
  url: urlOnDiffDomain,
  dataType: 'jsonp',
  data: {},
  success: function(data, textStatus) {
    alert('success...');
  },
  jsonpCallback: 'mycallback'
});

The success callback method is called when the server responds. The $.ajax method sets up a function that handles the response by calling the success callback method.

The most likely reason that the success method is not called, is that the response from the server is not correct. The $.ajax method sends a value in the callback query 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 $.ajax method has set up is never called.

If the server can not use the value in the callback query string to set the function name in the response, you can specify what function name the $.ajax method should expect from the server. Add the property jsonpCallback to the option object, and set the value to the name of the function that the server uses in the response.

If for example the $.ajax method 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:

jsonp12345({...});

If the server ignores the callback query string, and instead responds with something like:

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'
});
烟火散人牵绊 2024-08-31 01:01:37

通常,尝试

$.getJSON(urlOnDiffDomain, function(data, textStatus){
    alert('success...');
});

为我工作。您需要添加 &callback=?到 urlOnDiffDomain,其中 jQuery 自动替换 JSONP 中使用的回调。

错误回调不会被触发,但是你可以使用全局$.ajaxError,像这样

$('.somenode').ajaxError(function(e, xhr, settings, exception) {
    alert('failed');
});

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.

The error callback is not triggered, but you can use the global $.ajaxError, like this

$('.somenode').ajaxError(function(e, xhr, settings, exception) {
    alert('failed');
});
阳光①夏 2024-08-31 01:01:37

这不是您问题的完整答案,但我认为路过的人想知道这一点:

当您处理 来自 WCF REST 的 JSONP 尝试使用:

[JavascriptCallbackBehavior(UrlParameterName = "$callback")]

来实现您的服务;这将为您提供开箱即用的 JSONP。

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 REST try to use:

[JavascriptCallbackBehavior(UrlParameterName = "$callback")]

for your service implementation; this should give you JSONP out-of-the-box.

扛刀软妹 2024-08-31 01:01:37
    $.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);
                  }
            });
    $.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);
                  }
            });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文