php - HTTP 请求重复(Jquery/PHP)
问题描述
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
function Send1()
{
adress="1.php"
$.get(adress,Get1)
}
function Get1(answer)
{
$("#Show1").html(answer)
}
function Send2()
{
$("#Show1").click(function( event ) {
var cty = $(event.target).attr('id');
adress="2.php?cty="+ cty
$.get(adress,Get2)
})
}
function Get2(answer)
{
$("#Show2").html(answer)
}
</script>
</head>
<body>
<form method="post">
<div style="margin-top: 1vh; margin-bottom: 1vh;">
<input type="button" onclick="Send1()" style="height:4vh; width: 19.7vw;" value="Button">
</div>
</form>
<div id="Show1" style="border:1px solid black; height: 600px; width:300px; float:left; margin-right: 1vw;" onclick="Send2()"></div>
<div id="Show2" style="border:1px solid black; height: 600px; width:1000px;"></div>
</body>
</html>
1.php
<?php
require 'vendor/autoload.php';
$adress="http://localhost:3000/Country";
$clienthttp=new EasyRdf\Http\Client($adress);
$req=$clienthttp->request();
$resultJSON=$req->getBody();
$country=json_decode($resultJSON);
foreach ($country as $countries)
{
echo "<a href='#'><span id='$countries->id'> $countries->name </span></a> <br>";
}
?>
2.php
<?php
require 'vendor/autoload.php';
$cty = $_GET["cty"];
$adress="http://localhost:3000/City?CountryId=$cty";
$clienthttp=new EasyRdf\Http\Client($adress);
$req=$clienthttp->request();
$resultJSON=$req->getBody();
$city=json_decode($resultJSON);
echo "<div style='text-align: center; margin-bottom: 5vh;'>";
echo "<span style='font-size: 3vh'> Name </span>";
echo "<span style='margin-left: 10vw'> Surface </span>";
echo "<span style='margin-left: 10vw'> Population </span>";
echo "</div>";
foreach ($city as $cities)
{
echo "<div style='text-align: center; margin-bottom: 22.5vh;'>";
echo "<span style='font-size: 3vh;'> $cities->name </span>";
echo "<span style='margin-left: 10vw'> $cities->surface </span>";
echo "<span style='margin-left: 10vw'> $cities->population </span>";
echo "</div>";
}
?>
简短描述:第一个请求(Send1 和 Get1)显示国家列表。当我单击其中一个国家/地区时,我想从中获取城市(这就是 Send2 和 Get2 的用途)。由于某种原因,请求被重复 x 次(第一个请求执行一次,第二个请求执行两次,依此类推)。有时它只是随机改变来自不同国家的城市之间的值。基本上,代码可以工作,但会产生一些奇怪的行为。
解决方案
每次运行 Send2 时,它都会执行$("#Show1").click...
为 show1 按钮创建一个新的单击事件处理程序。但是您永远不会删除任何以前的处理程序。因此,当您单击 show1 时,它会运行曾经附加到按钮的所有处理程序(以及所有 Ajax 请求)。
第一次显然没问题,但之后触发的请求数量将与每次执行 Send2 函数成正比。通过单击 show1 触发 Send2 的事实也加剧了混乱!
在 Send2 函数之外定义一次事件处理程序会更有意义。事实上,您根本不需要 Send2 函数。
推荐阅读
- javascript - 待办事项列表应用程序 - ReactJS 上的 onChange 不起作用?
- c# - 如果 EF 导航属性具有默认值,则不会加载它们
- mysql - InnoDB 初始化警告
- python - 将混合嵌套字典转换为列表
- google-apps-script - 列出所有 Gmail 历史记录详细信息
- python - 在 Python 中单击按钮后更改后,我可以获取按钮上的文本吗?
- c++ - 无法在 C++ 中读取 CSV 文件
- python - 查找在基于类的视图中使用的模型的当前名称,然后将其用作两个过滤器参数之一
- flutter - 使用不包含 Bloc 类型的 Bloc 的上下文调用的错误 BlocProvider.of()
- java - 如何在 mySpringBoot application.yml 中配置 HikariCP?