Jquery未加载PHP文件

Jquery Not Loading PHP File

本文关键字:文件 PHP 加载 Jquery      更新时间:2023-09-26

我无法使用JQuery/Ajax将PHP文件的内容加载到div标记中。

这是我正在加载文件的页面:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function init() {
    reloadChat();
    setInterval (reloadChat, 5000);
}
function reloadChat() {
    $.ajax({  
        url: "chat.php",  
        cache: false,  
        success: function(){
            $("#chatmenu").load("chat.php");
        },  
    });  
}
</script>
<body onLoad='init()'></body>
<div id='chatmenu'></div>

我正在加载的PHP文件(chat.PHP)在同一个文件夹中,只是一个echo语句:

<?php echo "test"; ?>

为了确保我的Javascript函数没有问题,我在success函数下添加了一个警报,它确实每5秒提醒我一次,所以我认为这是load语句的问题。

直接使用.load(),无需首先发出Ajax请求:

function reloadChat() {
    $("#chatmenu").load("chat.php");  
}

更新:

我注意到,在您的示例代码中,您在div元素之前关闭了body标记。

<body onLoad='init()'></body> <!-- This ain't right --> 
<div id='chatmenu'></div>

试试这个:

<body onLoad='init()'>
    <div id='chatmenu'></div>
</body>

试试这个:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function init() {
    reloadChat();
    setInterval (reloadChat, 5000);
}
function reloadChat() {
    $.ajax({  
        url: "chat.php",  
        cache: false,  
        success: function(response){
            $("#chatmenu").text(response);
        },  
    });  
}
</script>
<body onLoad='init()'></body>
<div id='chatmenu'>
</div>

此外,为了上帝的爱,请使用最新版本的jQuery

看起来来自$.ajax的第一个请求将返回"test",然后您将其用作$("#chatmenu").load的URL。

试试这个:

function reloadChat() {
    $.ajax({  
        url: "chat.php",  
        cache: false,  
        success: function(data){
            $("#chatmenu").append(data);
        },  
    });  
}

或者,如果您想替换#chatmenu的内容,Christofer Eliasson发布的方法(您只需在reloadChat中调用$("#chatmenu").load("chat.php"))将起作用。

将其放在一起:

<!DOCTYPE html>
<html>
  <head></head>
  <body>
    <div id="chatmenu"></div>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
    <script type="text/javascript">
      $(function() {
        setInterval (function() { 
           $("#chatmenu").load("chat.php");
        }, 5000);
      });
    </script>
  </body>
</html>