【发布时间】:2021-07-29 00:55:52
【问题描述】:
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 函数。
-
非常感谢,您应该单独发表评论,以便我奖励和支持您。
-
完成,见下文 - 谢谢
标签: php jquery ajax http easyrdf