jquery - ajax代码行为不正确

时间:2013-05-05 12:56:58

标签: jquery ajax

我想知道我的代码有什么问题?它只是不正常。语法对我来说很好 - 基本上,如果加载的页面上存在一个名为'map_canvas'的div,那么应该调用一个名为initialize_google_maps的函数。

但即使页面上不存在map_canvas div,有时也会调用initialize_google_maps函数。更具体一点 - 即使没有map_canvas,它也会在第一次点击链接时被调用,然后它的行为正确。

$(document).on("ready", function(){

 console.log('load ajax when document starts'); 
  var ajax_loaded = (function(response) {        

    $(".page-content")

     .html($(response).filter(".page-content"));       

    $(".page-content .ajax").on("click",ajax_load);  


   });


//the function below is called by links that are described with the class 'ajax', or are in the div 'menu' 

var history = [];                 

var current_url_method;               

var ajax_load = (function(e) {  


console.log('load ajax on clicks');         
  e.preventDefault();               


  history.push(this);               
  var url =$(this).attr("href");          
  var method = $(this).attr("data-method");   

  if (current_url_method != url + method) {   
    console.log('url + method'); 
    current_url_method = url + method;      

    $.ajax({                  
      "url": url,               
      "type": method,                         
      "success": ajax_loaded,         
    });
   }

    if ($("#map_canvas").length > 0)
    {
      console.log('ajax 2 - map_canvas is detected'); 
      initialize_google_maps();

    }


});



$("#menu a").on("click",ajax_load);
$(".ajax").on("click",ajax_load);
$("#menu a.main").trigger("click");
$(".search-box form").on("submit", form_submit);

});

1 个答案:

答案 0 :(得分:1)

默认情况下,

.ajax是异步的。因此,在返回ajax响应之前,执行ajax调用之后的代码(在此处检查$("#map_canvas").length)将会执行。

 $.ajax({                  
      "url": url,               
      "type": method,                         
      "success": ajax_loaded         
    });

快速解决方案是使ajax调用同步:

$.ajax({                  
  url: url,               
  type: method,  
  async: false,                       
  success: ajax_loaded       
});

警告:同步调用非常讨厌并锁定浏览器,更好的解决方案是在ajax对象的响应中执行$("#map_canvas").length检查并保持调用异步。 / p>

$.ajax({                  
  url: url,               
  type: method,  
  async: true,                       
  success: function(){
     //Running your secondary checks here will ensure that they
     // are executed only when the Ajax object has finished what it has to do.
  }       
});