回调函数不工作后返回值

时间:2013-05-08 13:03:50

标签: javascript jquery

我不知道是否在一个有效的问题之下?或者只是我的愚蠢。

 function IsSlaExists(department) {
     var flag = "";
     $.ajax({
         type: "POST",
         data: "Type=ISSLAEXISTS&Department=" + encodeURI(escape(department)),
         url: "class-accessor.php",
         success: function (data) {
             //flag=data;  
             flag = "YES";
         }
     });
     return flag;
 }

 alert(IsSlaExists('department'));

我正在尝试返回flag的值,但即使我手动设置了flag的值,函数也会返回空白。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

$.ajax({
       type: "POST",
       data: "Type=ISSLAEXISTS&Department=" + encodeURI(escape(department)),
       url: "class-accessor.php"
}).done(function(r){
      alert("flag");
});

这会在AJAX请求成功时提供警报。 r将包含响应为您提供的数据。例如,您现在可以在处理请求的done函数内调用另一个函数。

由于$ .ajax返回promise,您可以只返回ajax调用,然后将函数链接在一起

function ajaxCall(department) {
    return  $.ajax({
           type: "POST",
           data: "Type=ISSLAEXISTS&Department=" + encodeURI(escape(department)),
           url: "class-accessor.php"
    });
}

ajaxCall("myDept").done(function(response){
   alert(response);
})
相关问题