0

我想知道我的代码有什么问题?它只是无法正常工作。语法对我来说很好——基本上,如果加载的页面上存在一个名为“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);

});
4

1 回答 1

1

.ajax默认情况下是异步的。所以本质上,ajax 调用之后的代码(你正在检查的地方$("#map_canvas").length)在你的 ajax 响应返回之前被执行。

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

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

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

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

$.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.
  }       
});
于 2013-05-05T13:05:30.543 回答