【问题标题】:no response from ajax in when methodwhen 方法中没有来自 ajax 的响应
【发布时间】:2016-05-24 16:58:11
【问题描述】:

在 $.when: 中调用 ajax 方法后我没有响应:

$.when(tht.ajax.getUserDrp()).done(function (data) {
    if(data)  console.log('hava data')
    else  console.log('no data')
});

getUserDrp 函数:

getUserDrp: function(){
  $.ajax({
    url: "../account/getLevel" ,
    type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
       // do somthing
    }
  });
}

结果总是在控制台打印“无数据”,为什么?

【问题讨论】:

  • 你的success函数里面的数据值是多少?

标签: jquery ajax


【解决方案1】:

你试图使用getUserDrp 作为一个承诺,但你没有返回$.ajax 函数结果,这就是为什么.done() 永远不会被调用。

试试:

getUserDrp: function(){
  return $.ajax({
    url: "../account/getLevel" ,
    type: "POST",
    contentType: "application/json; charset=utf-8"
  });
}

【讨论】:

    【解决方案2】:

    要使用when,done,你需要如下改变你的函数

    getUserDrp: function(){
      return $.ajax({
        url: "../account/getLevel" ,
        type: "POST",
        contentType: "application/json; charset=utf-8"
      });
    }
    

    您也可以使用回调代替

    getUserDrp: function(callback){
      $.ajax({
        url: "../account/getLevel" ,
        type: "POST",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
           callback(data)
        }
      });
    }
    
    getUserDrp(function(data){
    if(data)  console.log('hava data')
        else  console.log('no data')
    })
    

    【讨论】:

    • tnx 为您解答,但我需要知道为什么我的代码无法正常工作!
    • 你复制别人的答案只是为了提高你的分数,这不是很好,伙计。
    • 哈,没有复制你的答案,我们实际上是同时写的!最好总是做出有利的判断。万事如意!
    • @ykay 对不起。
    猜你喜欢
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多