我想知道如何通过 Jquery 显示 PHP 输出


I was wondering how do I display PHP output through Jquery?

我对jQuery和Ajax有点陌生,但无论如何,我想知道,我是否可以在使用jQuery显示PHP 0utput数据时获得一些帮助。

这是我的 html 文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Testing Out in PHP!!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type = "text/javascript" src="jquery1.js"></script>
<script type = "text/javascript">
$("#btnLoad").click(function(){
    $.ajax({
        type: 'POST',
        url: 'page1.php',
        success: function(data){
                 if(data != null) $("#content").text(data)
         }
     });
});
$(document).ready(function(){
    $("button").click(function(){
        $("div").empty();
    });
});
</script>
</head>
<body>
 <div id="content" style="height:100px; width:250px;background-color:yellow">
  This is some text
  <p>This is a paragraph inside the div.</p>
 </div>
 <input type="button" id="btnLoad" value="Load" />
 <button>Clear Contents </button>
</body>
</html>

这是我的简单PHP文件page1.php:

<?php
echo "This is the sample data to be printed";
?>

有什么方法可以将这两个文件关联起来,以便使用 Jquery 和 Ajax 将 php 文件的输出显示在 html 文件中

您已将$("#btnLoad").click()置于$(document).ready之外。更改您的脚本并将其移动到其中,然后单击将起作用:

<script type = "text/javascript">
$(document).ready(function(){
    $("button").click(function(){
        $("div").empty();
    });
    $("#btnLoad").click(function(){
        $.ajax({
            type: 'POST',
            url: 'page1.php',
            success: function(data){
                     if(data != null) $("#content").text(data)
             }
         });
    });
});
</script>

从下面的 javascript 代码中替换你的 javascript 代码:

$(function(){
    $("button").click(function(){
        $("div").empty();
    });
    $("#btnLoad").click(function(){
    $.ajax({
            type: 'POST',
            url: 'pager1.php',
            success: function(data){
                     if(data != null) $("#content").text(data)
             }
        });
    });
});