javascript - 文本字段显示“未定义”的 php 数据库?
问题描述
我正在尝试创建一个表单,当用户在一个文本字段中输入帐户代码时,帐户名称应在下一个文本字段中自动生成。数据库和表已经建立,但是当用户输入帐户代码时,帐户名称字段显示“未定义”。我是编码新手,我不确定如何解决这个问题。下面我附上了我的表单的样子,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 中的数组是零索引的,所以第一项的索引是0
,所以代码应该是:
document.getElementById("account_name").value = myObj[0];
推荐阅读
- jira - 如何使用 Jira Rest API 获取每个测试的前置条件
- javascript - 如何获得品牌属性的价值?
- javascript - 如何从网站 javascript 中获取价值?
- python - 重复高阶函数
- javascript - Angular - 输入预测值调用 api
- javascript - NodeJS:如何使用 Loopback4 建立多对多关系
- windows - 在 Windows 容器模式下的 Windows 10 上,Docker 拉取失败
- reactjs - 警告:无法对未安装的组件执行 React 状态更新......componentWillUnmount 方法
- python - Pandas 只合并 SQLite 数据库中的新数据
- python - 如何将 matplotlib.pypot 图保存为具有所需像素大小的图像?