javascript 选择值更改时,Ajax呼叫从数据库查询填充表单字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19957823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ajax call to populate form fields from database query when select value changes
提问by user2886669
I have been looking through the questions on here and cant find an exact answer to what i am after :( but i have managed to get something.
我一直在浏览这里的问题,但找不到我所追求的确切答案:(但我设法得到了一些东西。
i have a form select field which i populate from a db query
我有一个表单选择字段,我从数据库查询中填充
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
and then there are currently 2 other textboxes (might increase eventually) which i want to populate when the above select box value is changed/selected
然后当前还有 2 个其他文本框(最终可能会增加),我想在更改/选择上述选择框值时填充它们
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_email" value="" />
so i have an onchange function on my select box which is this
所以我的选择框上有一个 onchange 功能,就是这个
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").innerHTML += data[i].id + ' - ' + data[i].name + ' - ' + data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and my formdata.php file is like so
我的 formdata.php 文件就是这样
<?php
include("include/user.php");
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['bussinessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
which is making the ajax call correctly and returning the data expected but i now need help to populate the textbox values?
这是正确地进行 ajax 调用并返回预期的数据,但我现在需要帮助来填充文本框值?
can anyone please help me with this, have literatly spent ages trying to figure it out, im not familiar with javascript/json so not sure where to begin
任何人都可以帮我解决这个问题,已经花了很长时间试图弄清楚,我不熟悉 javascript/json 所以不知道从哪里开始
i want the company_name textbox value to be set to $cName; and company_email textbox value to be set to $cWeb;
我希望将 company_name 文本框值设置为 $cName;并将 company_email 文本框值设置为 $cWeb;
appreciate any help
感谢任何帮助
Luke
卢克
回答by user2886669
ok the solution that i used, for anyone else wanting to know how i solved it is
好的,我使用的解决方案,对于其他想知道我是如何解决它的人
my index.php which contains the javascript and the form code
我的 index.php 包含 javascript 和表单代码
javascript code
javascript代码
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("company_name").value="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("company_name").value = data[i].name;
document.getElementById("company_email").value = data[i].web;
}
}
}
xmlhttp.open("GET","formdata.php?q="+str,true);
xmlhttp.send();
}
</script>
and the form code
和表单代码
<select style="width:100%;" class="quform-tooltip chosen-select" id="company_select" name="company_select" title="Company Select" onChange="showUser(this.value)">
<option value="">Please select</option>
<?php
$userID = $user->getUserID();
$query = $user->database->query("SELECT * FROM tbl_businesses as business LEFT JOIN tbl_user_businesses as biz_user ON business.businessID = biz_user.businessID WHERE biz_user.userID ='$userID'");
while($row=$user->database->fetchArray($query))
{
$bizID = $row['businessID'];
$bizName = $row['businessName'];
echo "<option value='$bizID'>$bizName</option>";
}?>
</select>
<input id="company_name" type="text" name="company_name" value="" />
<input id="company_email" type="text" name="company_name" value="" />
then my formdata.php
然后我的 formdata.php
$q = intval($_GET['q']);
$sql="SELECT * FROM tbl_businesses WHERE businessID = '".$q."'";
$result = $user->database->query($sql);
$info = array();
while($row=$user->database->fetchArray($result))
{
$cID = $row['businessID'];
$cName = $row['businessName'];
$cWeb = $row['businessWebsite'];
$info[] = array( 'id' => $cID, 'name' => $cName, 'web' => $cWeb );
}
echo json_encode($info);?>
thats it, thanks to charlietfl for your help!
就是这样,感谢 charlietfl 的帮助!
hope this helps someone :)
希望这对某人有所帮助:)
回答by Dave
Here's an example with PHP and JQuery. If you are not familiar with JQuery, I suggest you take some time to digg into that before going on with your ajax, it's definitely gonna worth it. JQuery have methods like getand ajaxto do async request to the server.
这是 PHP 和 JQuery 的示例。如果您不熟悉 JQuery,我建议您在继续使用 ajax 之前花一些时间深入研究它,这绝对值得。JQuery 有像get和ajax这样的方法来向服务器发出异步请求。
Now, heres some jquery we used to get JSON data from the server.
现在,这是我们用来从服务器获取 JSON 数据的一些 jquery。
var title = '.....'
$.getJSON('getActivite.php?title=' + title, null,
function(data){
$("#currentId").val(data.ID);
$("#nomActivite").val(data.Nom);
$("#Description").val(data.Description);
$("#DateEvent").val(data.Date);
});
$("#currentId").val(data.ID); , this says : find the element with the id currentId in the DOM, and change it's value to the property ID of the data received from the ajax call.
$("#currentId").val(data.ID); ,这表示:在 DOM 中找到具有 id currentId 的元素,并将其值更改为从 ajax 调用接收到的数据的属性 ID。
On the PHP side, they had
在 PHP 方面,他们有
<?php
header('Content-Type: application/json');
mysql_connect("localhost","root") or die (" NOPE . [" . mysql_error() . "]");
mysql_select_db("garderie");
$title = $_GET["title"]; // we received this from the json call
$query = " select a.ActiviteID as ActiviteID , rtrim(a.Nom) as Nom, a.Description from activites a inner join .....' ";
$result = mysql_query($query);
$ligne = mysql_fetch_array($result);
$data = array(
'ID' => $ligne["ActiviteID"],
'Nom' => $ligne["Nom"],
'Description' => $ligne["Description"],
'Date' => $date
);
mysql_close();
echo (json_encode($data));
?>