2012-06-27 36 views
0

我希望當我在文本鍵入它應該加載人如何使用JavaScript將數據加載到表單中?

<html> 
<head> 
    <script type="text/javascript"> 
    function FetchUser(str) 
{ 
if (str=="") 
    { 
    document.getElementById("txtHint").innerHTML=""; 
    return; 
    } 
if (window.XMLHttpRequest) 
    { 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    { 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    var data = JSON.parse(xmlhttp.responseText); 
    } 
    } 
xmlhttp.open("GET","finduser.php?q="+str,true); 
xmlhttp.send(); 
} 
this.form.name.value=data.name; 
this.form.age.value=data.age; 
</script> 
</head> 
<body> 
<form method="post" > 
Id<input type="text" name="id" size="5" /> </br> 
Name<input type="text" id="name" name="name" onclick="Fetchuser(this.form.id.value)" ></br> 
Age<input type="text" id="age" name="" size="2" /></br> 
</form> 
</body> 
</html> 

爲PHP代碼的名稱從MySql數據庫的數據加載到一個HTTP表單 。

<?php 
$q=$_GET["q"]; 
$con = mysql_connect('localhost', 'root', '125'); 
if (!$con) 
    { 
    die('Could not connect: ' . mysql_error()); 
    } 

mysql_select_db("test", $con); 

$sql="SELECT * FROM wow WHERE id = '".$q."'"; 
$resul = json_encode(mysql_query($sql)); 
echo $resul; 
?> 

我的問題是我怎麼能同時獲得文本框的名稱和年齡。 我試過這個,但我仍然不能加載數據

+0

[Load mySQL Data Into Form]可能重複(http://stackoverflow.com/questions/7125990/load-mysql-data-into-form) –

+0

你可以簡單地使用[json](http://php.net) /manual/en/book.json.php)。 – Leri

+0

不要忘記回顯你的php代碼的輸出,所以你可以期待一個非空的responseText –

回答

2

你可以使用json_encode返回一個json與所有相關的字段,並在JavaScript把它放在它所屬的每個字段。

$result = json_encode(mysql_query($sql)); 
echo $result; // don't forget to push the output or responseText is null. 

而且在JavaScript:

var data = JSON.parse(xmlhttp.responseText); 

然後你data.name_of_the_field

+0

+1來建議正確的方式來輕鬆地傳遞和解析數據。 –

+0

感謝德克斯特指出缺少的回聲。 解決方案應該在你自己的例子中工作。只需檢查「data」變量在javascript中的值是否正確。 – iwiznia

0

把一個id<input id="name"<input id="age"在文本框中訪問您的數據,這樣你就可以通過爲它們分配document.getElementById("name"),document.getElementById("age")

1
<?php 
$rs=mysql_fetch_object($result); 
$name=$rs->name; 
$age=$rs->age; 
?> 
    Name<input type="text" name="name" value="<?php echo $name;?>" /> 
    Age<input type="text" name="" size="2" value="<?php echo $age;?>" /> 
+0

+1基本上,是 – Wh1T3h4Ck5

+0

我認爲他想要一個自動提示功能,所以基本上ajax請求是必須的,而不是這個解決方案。 –

+0

@ Wh1T3h4Ck5我想他想要一個自動提示功能。 –

相關問題