首页 > 解决方案 > jquery和php之间使用GET交互

问题描述

我想编写一个网页并使用 jquery 从服务器上的 php 获取少量数据,但在同一个文件中,当我单击一个按钮时。我想发送 ?nm=bill 并用“bob”回答。我按下按钮,但它似乎没有到达服务器。我得到了将查询发送到的文件的内容。在按下按钮之前,我清除了浏览器、Firefox、历史记录。这是代码。

<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
  $("#btn").click(function(){
    console.log("btn pressed");
    $.get("a_foo.php?nm=bill", function(data, status){
      alert("Data:\n" + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>

<body>
<?php
$rsp = "7 come 11";
?>

<button id="btn">Send</button>

<p id="rch"><?php echo $rsp; ?> </p> 

<body>

<?php
if ($_SERVER["REQUEST_METHOD"] == "GET"){
  var_dump($_SERVER["REQUEST_METHOD"]);
  if ($_SERVER['QUERY_STRING']) {
    echo "bob";
  }
}

?>

</body>
</html>

标签: phpjquery

解决方案


当前请求的目标是 a_foo.php 我修复它并显示 bob 如果 get nm 是 bill 否则显示 html

<?php
$_nm = $_GET["nm"];
if($_nm == "bill"){
    echo "bob";
}
else
{
?>  
<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
    $("#btn").click(function(){
        console.log("btn pressed");
        $.get("?nm=bill", function(data, status){
          alert("Data:\n" + data + "\nStatus: " + status);
        });
    });
});
</script>
</head>
<body>
<?php
$rsp = "7 come 11";
?>
<button id="btn">Send</button>
<p id="rch"><?php echo $rsp; ?> </p> 
<body>
</body>
</html>
<?php
}
?>

推荐阅读