假设我要对服务器进行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;
});

最佳答案

第二个不是选择。当您取出功能时;

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。

关于javascript - jQuery-replaceWith与ajax调用之间的区别,反之亦然,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9738014/

10-12 13:04
查看更多