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 EasyRdfHttpClient($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 EasyRdfHttpClient($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函数的每次执行而不断增加。Send2是通过点击show1触发的,这一事实也加剧了混乱!

在Send2函数之外定义一次事件处理程序会更有意义。事实上,您根本不需要Send2函数。

最新更新