Jquery成功函数不使用JSONP触发 [英] Jquery success function not firing using JSONP

查看:104
本文介绍了Jquery成功函数不使用JSONP触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在做一些使用jQuery调用我在不同域上的服务。成功调用服务(我的调试点被触发),并返回正确的响应(我嗅探流量)。

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

我的问题主要是成功和失败的回调不会被解雇。我读过一些其他帖子表示使用JSONP时未触发错误事件。这是成功事件的情况(也许是因为我假设我提供自己的回调函数),或者有没有办法解雇我的成功回调。提前致谢。

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响应直接写入响应 stream 。简单地返回一串JSON不会这样做,你需要有人构造它并将其流回。如果您确实这样做,我原始帖子中的代码将正常工作。

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.

服务代码示例:

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

如果有更好的方法可以做到这一点,我很满意。对于其他所有人,我知道在WCF 4.0中对JSONP有一些原生支持的概念。此外,您可能想要做一点检查出于安全目的 - 尽管我没有进行太多调查。

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.

这篇关于Jquery成功函数不使用JSONP触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆