28

一直在使用 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....');
  }
}); 
4

5 回答 5

19

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.

于 2010-03-04T22:56:20.163 回答
14

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

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

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'
});
于 2010-03-04T16:05:00.147 回答
0

尝试

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

通常对我有用。您需要添加 &callback=? 到 urlOnDiffDomain,其中 jQuery 会自动替换 JSONP 中使用的回调。

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

$('.somenode').ajaxError(function(e, xhr, settings, exception) {
    alert('failed');
});
于 2010-03-04T16:03:49.440 回答
0

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.

于 2012-07-30T10:15:03.777 回答
0
    $.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);
                  }
            });
于 2012-09-27T17:10:29.033 回答