2012-03-16 86 views
0

假設我想對服務器進行ajax調用並使用響應替換現有文檔內容的一部分。會有什麼理由選擇這些方法之一嗎?jQuery - replaceWith與Ajax調用之間的區別或反之亦然

選項1 - 進行ajax調用,並從錯誤/成功函數中執行replaceWith。例如:

$.ajax({ 
     type  : 'GET', 
     url  : '/some/path/here', 
     success : function(data) { 
     // process data here 
     $('#container').replaceWith(processedData); 
     } 
}); 

選項2 - 呼叫replaceWith,傳遞函數使所述AJAX調用。例如:

$("#container").replaceWith(function(){ 
    var responseData; 
    $.ajax({ 
     type  : 'GET', 
     url  : '/some/path/here', 
     success : function(data) { 
     // process data here 
     responseData = processedData; // 
     } 
    }); 
    return responseData; 
}); 
+0

ProcessedData從未給出任何價值。 – 2012-03-16 13:24:51

回答

4

第二個不是一個選項。當你拿出這個功能時,

function(){ 
    var responseData; 
    $.ajax({ 
     type  : 'GET', 
     url  : '/some/path/here', 
     success : function(data) { 
     // process data here 
     responseData = processedData; // 
     } 
    }); 
    return responseData; 
} 

這將返回undefined。原因是,當時間函數運行並返回時,reponseDataundefined。僅在將來的某個時間,success函數會執行並設置responseData。但是,您的replaceWith代碼已經完成執行。

圍棋與選項1

+0

感謝您的幫助! – csturtz 2012-03-16 13:34:56

2

選項1是你唯一的選擇,因爲選項2是行不通的通話將異步執行。這意味着你的函數不會返回任何東西。

如果您正在尋找外化從您的AJAX調用返回的數據的處理,只需設置success參數爲要執行的函數的引用:

$.ajax({ 
    type: 'GET', 
    url: '/some/path/here', 
    success: processData 
}); 

function processData(data) { 
    // process data here 
    $('#container').replaceWith(data); 
} 
+0

感謝您的幫助! – csturtz 2012-03-16 13:34:49

相關問題