【问题标题】:Ajax calls hitting web server but no callback functions get executedAjax 调用访问 Web 服务器,但没有执行回调函数
【发布时间】:2017-12-14 16:11:22
【问题描述】:

ajax函数

function Verify(ccode,dgh)
{
    str = "ccode="+ccode+"&dgh="+dgh;
    console.log(str);//this outputs means that this functions gets called
    $.ajax({
        type: "POST",
        url: "ajax/verify",
        data: str,
        async: false,
        cache: false,
        error: function (xhr, ajaxOptions, thrownError)
        {
            console.log(xhr.status);
            console.log(thrownError);                         
        },
        success: function(json)
        {
            console.log("in-fun: "+json.code); //does not gets executed
            return json.code; //does not return value
        },
        failure:function(response)
        {
            console.log("Ajax call failed"); //does not executes
        }
    });
}

上面的ajax函数被称为var e = Verify(var1, var2); e 的值在 ajax 请求后未定义。

ajax 请求确实到达了我的 Web 服务器,并且在 apache 日志和开发工具中可见,并返回 200 OK。 Ajax 端点正在工作并且确实返回了一个有效的 json。页面输出头也设置为json

编辑:更新了上面的代码

function Verify(ccode,dgh)
{
    var retData = '';
    str = "ccode="+ccode+"&dgh="+dgh;
    console.log(str); // this works
    $.ajax({
        type: "POST",
        url: "ajax/verify",
        data: str,
        async: false,
        cache: false,
        error: function (xhr, ajaxOptions, thrownError)
        {
            console.log(xhr.status); //does not gets called
            console.log(thrownError);

        },
        success: function(json)
        {
            console.log("in-fun: "+json.code); //this does not ouputs anything
            retData = json.code;
        },
        complete:function(response)
        {
            console.log("Complete called"); //does not gets called
        }
    });
    return retData;
}

【问题讨论】:

  • failure: -> error:
  • 这个函数没有返回任何东西,所以赋值使用undefined
  • async: false, -> (blank)
  • @MaxZoom 是的,这让我很困扰
  • failure: 据我所知,$.ajax() 中不存在。 console.log 可能无法正常工作,因为您没有得到预期的回复(这就是错误:函数获取 console.logged 的​​原因)。检查控制台中的响应是否符合您的预期。我觉得这可能与 dataType 有关。然而,这只是一个猜测。文档:api.jquery.com/jquery.ajax

标签: jquery ajax


【解决方案1】:

由于已经使用了 jQuery AJAX 调用,您可以依赖它的 deferred object,如下所示:

function Verify(ccode, dgh)
{
  var str = "ccode="+ccode+"&dgh="+dgh;
  console.log(str);  //debug outputs
  return $.ajax({
      type: "POST",
      url: "ajax/verify",
      data: str
   });
}

Verify(var1, var2).done(function(json) {
  if (json) {
    var e = json.code;
    // more code for the success case
  }
  else {
    console.log("Invalid server response"); 
  }
}).fail(function() {
  console.log("Ajax call failed"); 
});

【讨论】:

  • 请注意done()fail() 调用在Verify() 函数之外,并使用jqXHR 对象特性。我同意e除了在成功案例中使用之外没有真正的意义。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-28
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多