2013-11-25 36 views
3

只是我想从两个php页面使用jquery加载数据。我把下面的代码放在一起,但只有一个不能同时工作。有任何想法吗?来自一个页面的两个ajax请求

$(document).ready(function() { 
     loadData(); 
    }); 

    var loadData = function() { 
     $.ajax({  
      type: "GET", 
      url: "second.php",    
      dataType: "html",     
      success: function(response){      
       $(".hm_m_un").html(response); 
       setTimeout(loadData, 1000); 
      } 

     }); 
    }; 
    $(document).ready(function() { 
     loadData(); 
    }); 

    var loadData = function() { 
     $.ajax({  
      type: "GET", 
      url: "test.php",    
      dataType: "html",     
      success: function(response){      
       $(".rx").html(response); 
       setTimeout(loadData, 1000); 
      } 

     }); 
    }; 

回答

2

你已经命名它们都是一样的。尝试一些合并

$(document).ready(function() { 
    window.setInterval(function() { loadData('second.php', $('.hm_m_un')); }, 1000); 
    window.setInterval(function() { loadData('test.php', $(".rx")); }, 1000); 
}); 

var loadData = function(page, ele) { 
    $.ajax({  
     type: "GET", 
     url: page,    
     dataType: "html",     
     success: function(response){      
      ele.html(response); 
     } 

    }); 
}; 
+0

我需要在不同的地方显示结果,这就是为什么我有两个类。 – user3006683

+0

我明白,但通过在你的函数中传递'jQuery'对象,你不需要重复你的代码。你现在只需要一个功能。 – Machavity

+0

我试过你的代码,但它不起作用。 – user3006683

3

您正在覆盖第一个loadData变量。给它一个不同的名字,你会没事的。

作为说明,您不需要调用$(document).ready()两次,您可以在技术上称它为一次。我会写这样的东西,如:

function descriptiveFunctionName() { 
    $.ajax({  
     type: "GET", 
     url: "second.php",    
     dataType: "html",     
     success: function(response){      
      $(".hm_m_un").html(response); 
      setTimeout(loadData, 1000); 
     } 
    }); 
} 

function anotherDescriptiveFunctionName() { 
    $.ajax({  
     type: "GET", 
     url: "test.php",    
     dataType: "html",     
     success: function(response){      
      $(".rx").html(response); 
      setTimeout(loadData, 1000); 
     } 
    }); 
} 

$(document).ready(function() { 
    descriptiveFunctionName(); 
    anotherDescriptiveFunctionName(); 
}); 

请注意,虽然这是一个非常懒惰的答案,用户Machavity的代码更重用更好,虽然你可能想只用发送到loadData更多回调未来的灵活性。

+0

感谢这一个也工作,但正如你所建议我使用Machavity的代码。 – user3006683

1

非常简单....您声明变量loadData并将其分配给一个函数。

然后,您使用相同的变量分配给另一个函数,从而消除第一个实例。使用不同的变量名称

相关问题