【发布时间】:2021-07-18 13:34:15
【问题描述】:
我正在尝试创建一个表单,当用户在一个文本字段中输入帐户代码时,帐户名称应在下一个文本字段中自动生成。数据库和表已经建立,但是当用户输入帐户代码时,帐户名称字段显示“未定义”。我是编码新手,我不确定如何解决这个问题。下面我附上了我的表单的样子,javascript 代码和 PHP 代码。 我的表单
脚本:
// onkeyup event will occur when the user
// release the key and calls the function
// assigned to this event
function GetDetail(str) {
if (str.length == 0) {
document.getElementById("account_name").value = "";
return;
}
else {
// Creates a new XMLHttpRequest object
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
// Defines a function to be called when
// the readyState property changes
if (this.readyState == 4 &&
this.status == 200) {
// Typical action to be performed
// when the document is ready
var myObj = JSON.parse(this.responseText);
// Returns the response data as a
// string and store this array in
// a variable assign the value
// received to first name input field
document.getElementById
("account_name").value = myObj[1];
}
};
// xhttp.open("GET", "filename", true);
xmlhttp.open("GET", "cashVoucher.acc.php?user_id=" + str, true);
// Sends the request to the server
xmlhttp.send();
}
}
PHP:
<?php
// Get the user id
$account_code = $_REQUEST['account_code'];
// Database connection
$con = mysqli_connect("localhost", "root", "", "general_ledger_account");
if ($user_id !== "") {
// Get corresponding first name and
// last name for that user id
$query = mysqli_query($con, "SELECT account_name FROM ledger_account WHERE account_code='$account_code'");
$row = mysqli_fetch_array($query);
// Get the first name
$name = $row["account_name"];
}
// Store it in a array
$result = array("$name");
// Send in JSON encoded form
$myJSON = json_encode($result);
echo $myJSON;
?>
表格:
<div class="form-group">
<label>Account Code</label>
<input type="text" class="form-control" id="account_code" name="account_code" placeholder="Debit or Credit Account Code" onkeyup="GetDetail(this.value)" value="">
</div>
<div class="form-group">
<label>Account Name</label>
<input type="text" class="form-control" id="account_name" name="account_name" placeholder="Debit or Credit Account Name" value="">
</div>
【问题讨论】:
标签: javascript php mysql xmlhttprequest