2016-10-15 43 views
0

我想等到ajax调用返回并且比处理代码,所以我有这个代码用于ajax调用。JavaScript自定义回调函数没有执行

function ajax(data, url, method, callback) { 

     $.ajax({ 
       url: url, 
       data: JSON.stringify(data), 
       method: method, 
       dataType: "application/json", 
       contentType: "application/json; charset=utf-8" 
     }).always(function (data, textStatus) { 
       callback(); 
      }); 
    }; 

vm.app.ajax({data}, "url", "post", function() { 
    alert('cdndvnidvndi'); 
}); 

但是我从来没有在回调函数内部接收调用。我在做什么错了吗?

回答

0

我无法找到任何错误接受dataType。但是这个代码适合我。

var vm = {app:{ajax}} 
 

 
function ajax(data, url, method, callback) { 
 

 
    $.ajax({ 
 
    url: url, 
 
    data: JSON.stringify(data), 
 
    method: method, 
 
    dataType: "json", // change the dataType to just 'json' 
 
    contentType: "application/json; charset=utf-8" 
 
    }).always(callback); // there is no reason to wrap the callback in a function 
 
}; 
 

 
vm.app.ajax({ 
 
    data: 'none' 
 
}, "https://jsonplaceholder.typicode.com/posts/1", "get", function(response) { 
 
    console.log(response); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

其实ajax是应用程序对象中的一个函数,我从另一个对象调用。一切工作正常,我可以看到很好的结果,但它从来没有达到回调函数。 – Epistemologist

0

我尝试解决这个问题,以改变我的代码来代替回调()。 在我的代码中使用echo json_encoder($ data);其中我不会在我的视图页面和AJAX提交表单像$数据传递值:

$.ajax({ 
      type: 'post', 
      dataType: 'json', 
      url: url, 
      data: 'search=' +search, 
      success: function (data) { 
       alert(data);//resend data get here 
       } 
     }); 

使用这种类型的代码中使用。

+1

我知道英语不是每个人的第一语言,但我真的不知道你在说什么。我真的不知道这是一个真正的答案还是只是一个评论。 – Mike