php - 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>
解决方案
当前请求的目标是 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
}
?>
推荐阅读
- javascript - 不要使用JS加载在dom中显示为none的div
- reactjs - 将图像上传到 Imgur 的身份验证错误
- reactjs - 用 redux 计算总数
- reactjs - 在 Next.js 上提供静态文件的身份验证?
- cmake - 从父 cmake 动态/静态库构建 cmake 静态库的最佳方法
- python - 在没有终端或任何应用程序打开的情况下运行 python 脚本
- php - 错误:用户 'db_max247' 已超出 'max_user_connections' 资源
- python - 附加到两个数组的更多pythonic方式
- spring-boot - Spring Kafka Listener 暂停消息处理一段时间
- python - 使用条件结果列连接 PySpark 数据帧