我有一个无法解决的问题。我对 Ajax 和 PhP 相当陌生,因此我将不胜感激我能得到的任何帮助。
我的本地主机上有一个数据库。我试图实现的是从服务器获取包含数据库信息的响应。我想将该信息存储在一个变量中,以便稍后可以在某个位置“回显”。
这背后的整个想法是:
您在输入字段中输入产品编号。请求正在发送到数据库。一旦您收到数据库的响应,产品编号下方的另一个输入字段将自动填写产品名称。单击下一步,您将再次看到输入字段,其中根据您之前输入的产品编号填充了其余信息。
到目前为止,问题是一旦所有内容发送完毕,我就可以立即得到回复,但如果我只想查看一条信息,然后“回显”其他所有信息,但我不知道该怎么做。
我希望我确实能够解释我的问题是什么,如果没有,我会尝试添加更多有关它的信息。
这是我的 Ajax 代码。我不知道如何存储从数据库获取的信息,以便稍后使用。
<script>
function showPump(str) {
if (str == "0") {
document.getElementById("pumpInfo").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pumpInfo").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getpump.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML 部分:
<form>
Product number:<input type="text" name="productNR" onfocusout="showPump(this.value)">
</form>
<br>
<div id="pumpInfo"><b>Pump info will be below</b></div>
PHP
mysqli_select_db($con,"pumps");
$sql="SELECT * FROM pumps WHERE product_nr = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo "Product type <input value=" . $row['type'] . "></br>";
}
mysqli_close($con);
?>
最终结果是,一旦我填写了产品编号字段,“结果”(产品类型)就会显示在其正下方,但我还有 4 个数据库条目希望在下一步中使用。
最佳答案
这是存储您通过 AJAX 接收的值的一种方法。
//results will be an array
var results;
if (this.readyState == 4 && this.status == 200) {
document.getElementById("pumpInfo").innerHTML = this.responseText;
results.push(this.responseText); //push the value of this.reponseText to the array.
}
//this pops the value of the first element of the results array
alert(results[0]);
关于javascript - Ajax 接收来自服务器的响应并将其保存在变量中以供以后 PhP 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42933594/