2012-03-13 67 views
0

我試圖根據AJAX函數的響應返回true或false的函數,但我不知道該怎麼做。如何在JavaScript中將AJAX函數中的值返回給父項?

(function($) { 
    $('#example').ajaxForm({ 
     beforeSubmit : function(arr, $form, options) { 

      var jsonStuff = JSON.stringify({ stuff: 'test' }); 

      $.post('/echo/json/', { json: jsonStuff }, function(resp) { 

       if (resp.stuff !== $('#test').val()) { 
        // Cancel form submittion 
        alert('Need to type "test"'); 
        return false; // This doesn't work   
       } 

      }, 'json'); 

     }, 
     success : function() { 
      alert('Form sent!'); 
     } 
    }); 
})(jQuery);​ 

我做了一個小提琴來說明這更好:

http://jsfiddle.net/vengiss/3W5qe/

我使用jQuery和Malsup的Ajax表格插件,但我認爲這種行爲是獨立的插件,我只需要到return falsebeforeSubmit函數取決於POST請求,所以表單不會每次都提交。任何人都可以將我指向正確的方向嗎?

在此先感謝!

+5

歡迎** **異步的奇妙世界!你不能那樣做。 – SLaks 2012-03-13 23:29:03

+0

可能重複的[jQuery:返回數據ajax調用成功後](http://stackoverflow.com/questions/5316697/jquery-return-data-after-ajax-call-success) – 2012-03-13 23:31:00

+0

FYI,如果你把你的代碼裏面'ready'處理程序,它已經獲得'jQuery'作爲第一個參數傳遞,所以你可以簡單地刪除直接函數調用:'jQuery(function($){... code here ...});'' – 2012-03-13 23:33:08

回答

6

處理異步函數時,這是不可能的。調用post的函數將立即返回,而ajax回調將在未來的某個點返回。從現在返回未來的結果是不可能的。

您需要做的是將回調傳遞給原始函數。此功能將最終將與AJAX調用

var makePostCall = function(callback) { 
    $.post('/echo/json/', { json: jsonStuff }, function(resp) { 
    if (resp.stuff !== $('#test').val()) { 
     // Cancel form submittion 
     alert('Need to type "test"'); 
     callback(false); 
    } else { 
     callback(true); 
    }}, 'json'); 
}; 

的結果稱爲然後切換其預期從makePostCall到使用回調而不是提示響應的代碼。

// Synchronous version 
if (makePostCall()) { 
    // True code 
} else { 
    // false code 
} 

// Async version 
makePostCall(function (result) { 
    if (result) { 
    // True code 
    } else { 
    // False code 
    } 
}); 
0

你可以把異步:假參數Ajax請求,那麼你可以控制未來的反響,結果發回給母公司。看到下面的內***
附加封閉主線:功能(即數據){

//before upload file check server has that file already uploaded 
     ***var flag=false;*** 
     $.ajax(
      { 
       type: "POST", 
       dataType:'json', 
       url:"xyz.jsp", 
       ***async:false,*** 
       data:{ 
         filename : upload_filename, 
         docname : upload_docname, 
         userid : upload_userid, 
        }, 
       success:function(data) 
       { 
        ***flag=true;*** 
       }, 
       error:function(request,errorType,errorMessage) 
       { 
        alert ('error - '+errorType+'with message - '+errorMessage); 
       } 
     }); 

     ***return flag;*** 

     } 
相關問題