我正在使用 AJAX 来访问 php 文件中的数据。 我对从数据库中检索到的数据的格式有疑问,请帮忙。
所以,这是我的 ajax 函数拼接。它从 find_account.php 中检索数据
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
form_prof.prof_id.value = req.responseText;
form_prof.prof_name.value = req.responseText;
form_prof.prof_username.value = req.responseText;
form_prof.prof_password.value = req.responseText;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
查找帐户.php
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
echo 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$id = $arr['profs_number'];
$name = $arr['profs_name'];
$username = $arr['profs_username'];
$password = $arr['profs_password'];
}
header("Content-type: text/plain");
echo $id;
echo $name;
echo $username;
echo $password;
?>
我的 HTML 中有 4 个输入框,req.responseText 从中输入值
每次我在输入字段中搜索名称时,例如:
Search: [ Dorothy Perkins ]
输出像 [id,name,username,password]:
[20111Dorothy Perkinsdperkins@mail.com123456] [same with 1st field] [same] [same]
我希望它像...
[20111] [Dorothy Pekins] [dperkins@mail.com] [123456]
其中 [ ] 是输入字段。 请帮我安排一下我的格式,我很困惑。我对此很陌生。
最佳答案
您可以在发送回之前在 json 中对返回值进行编码。 在 PHP 中
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
$returnValues = 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$returnValues = json_encode($arr);
}
echo $returnValues;
?>
在 JavaScript 中
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
req = JSON.parse(reg);
form_prof.prof_id.value = req.id;
form_prof.prof_name.value = req.name;
form_prof.prof_username.value = req.username;
form_prof.prof_password.value = req.password;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
关于javascript - 使用 AJAX 从一个 php 文件中获取多个数据并将它们插入不同的输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21597254/