我有一个表格,当用户选择一个地方时,我需要在文本框中获取数据。如果用户选择一个地点,则以下名称和金额将出现在以下文本框中。我已经完成了以下操作,但它不起作用。有人可以帮我吗?
我尝试了以下内容:
html
<div>
<label for="" class="">Place</label>
<select name="place" id="place" onchange="myplace();">
<option value="">--Option from db--</option>
</select>
</div>
<div>
<label for="" class="">Name</label>
<input type="text" name="myname" id="myname" value="<?php //if there is data in databas then it is shown here...otherwise the value will change according to the above selection?>" >
</div>
<div>
<label for="" class="">Amount</label>
<input type="text" name="myamnt" id="myamnt" value="<?php //if there is data in databas then it is shown here...otherwise the value will change according to the above selection?>" >
</div>
mysql:
if(!empty($_POST["myinitplace"]))
{
$sql = "SELECT * FROM all_data , my_place WHERE all_data.place=my_place.place and all_data.place = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_POST["myinitplace"]);
$stmt->execute();
$result = $stmt->get_result();
while($rows = $result->fetch_assoc())
{
$data['name']=$rows['name'] ;
$data['myacc']=$rows['amount'] ;
}
echo json_encode($data);
}
ajax
function myplace()
{
var a = document.getElementById("place").value;
//alert(a);
$.ajax({
type : "POST",
data : {
myinitplace : a
},
dataType : "JSON",
success : function(data){
document.getElementById("myname").value = data.name;
document.getElementById("myamnt").value = data.myacc;
}
})
}
分析解答
首先,我假设您已经在以下行中填充了Select Block,并具有有效的数据:
<option value="">--Option from db--</option>
例如
<option value="Place1">Place1</option>
<option value="Place2">Place2</option>
在这种情况下,您需要稍微修改HTML代码,以便它明确调用PHP脚本(通过指定URL),因此请在Ajax块中添加该行:
url: "xxxx.php",
假设PHP脚本的名称是testSO3Sept2023.php
,则HTML将为:
<script
src="https://code.jquery.com/jquery-3.7.1.js"
integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4="
crossorigin="anonymous"></script>
<div>
<label for="" class="">Place</label>
<select name="place" id="place" onchange="javascript:myplace();">
<option value="">Please select</option>
<option value="Place1">Place1</option>
<option value="Place2">Place2</option>
</select>
</div>
<div>
<label for="" class="">Name</label>
<input type="text" name="myname" id="myname" value="" >
</div>
<div>
<label for="" class="">Amount</label>
<input type="text" name="myamnt" id="myamnt" value="" >
</div>
<script>
function myplace()
{
var a = document.getElementById("place").value;
//alert(a);
$.ajax({
type : "POST",
data : {
myinitplace : a
},
url: "testSO3Sept2023.php",
dataType : "JSON",
success : function(data){
document.getElementById("myname").value = data.name;
document.getElementById("myamnt").value = data.myacc;
}
})
}
</script>
您可以通过此沙箱查看结果