2012-03-16 56 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