2014-12-07 81 views
0

fieled我有兩個領域在我的數據庫 卷號和名稱 我設計了一個HTML表單,其中有兩種輸入類型 一個 - >「卷沒有」 等是「姓名」填充一個當進入其他相關領域

我希望當我在卷號字段中輸入卷號並按Tab鍵時,名稱字段應該從數據庫中自動填充。

我的代碼在這裏

的index.php

<html> 

<head> 
<script type="text/javascript" src="jquery-1.7.1.min.js"></script> 
<script type="text/javascript"> 
var searchTimeout; //Timer to wait a little before fetching the data 
$("#roll").keyup(function() { 
    searchKey = this.value; 

    clearTimeout(searchTimeout); 

    searchTimeout = setTimeout(function() { 
     getUsers(searchKey);  
    }, 400); //If the key isn't pressed 400 ms, we fetch the data 
}); 


function getUsers(searchKey) { 
    $.ajax({ 
     url: 'getUser.php', 
     type: 'POST', 
     dataType: 'json', 
     data: {value: searchKey}, 
     success: function(data) { 
      if(data.status) { 
       $("#name").val(data.userData.name); 
      } else { 
       // Some code to run when nothing is found 
      } 
     } 
    });   
} 

</script> 


</head>    

<table> 
<tr> 
    <td>Roll</td> 
    <td><input type="text" name="roll" id="roll" /></td> 
</tr> 

<tr> 
    <td>Name</td> 
    <td><input type="text" name="name" id="name" /></td> 
</tr> 
</table> 
</html> 

getUser.php

<?php 
include "db.php"; 

$response = Array(); 

$response['status'] = false; 

$query = mysql_query("SELECT `name` FROM `tab` WHERE `roll` LIKE '%".$_POST['value']."%' LIMIT 1"); //Or you can use = instead of LIKE if you need a more strickt search 

if(mysql_num_rows($query)) { 
    $userData = mysql_fetch_assoc($query); 

    $response['userData'] = $userData; 
    $response['status'] = true;    
} 

echo json_encode($response); 
?> 
+2

聽起來像AJAX的工作 – 2014-12-07 19:53:34

+0

但如何?我該如何做到這一點 – 2014-12-07 20:27:36

+1

要廣泛,你需要做一些工作做一個嘗試,如果\當你遇到問題要求*代碼* – 2014-12-07 20:29:59

回答

0

可以使用做到這一點210。 AjaxPHP進行實時通信,所以名稱字段會自動填充而不用按下提交按鈕。

XMLHttpRequest()是需要做這個任務的功能。請做一些關於XMLHttpRequest()的研究,這將有助於你獲得更好的主意。

function auto(roll){ 
    var roll=roll; 
    var ajax=new XMLHttpRequest(); 
    ajax.open("post","yourfile.php",true);  
    ajax.setRequestHeader("content-type","application/x-www-form-urlencoded"); 
    ajax.onreadystatechange=function(){ 
    if(ajax.readyState == 4 && ajax.status == 200){ 
     document.getElementById(Name).value=ajax.responseText; //This line will fill the Name field automatically 
    } 
    } 

    ajax.send("roll_num="+roll); 
} 

所以,在這種情況下,你的PHP文件yourfile.php,取namerollechoname在PHP文件,並name值將傳遞給阿賈克斯asynchronously。那麼在name域將自動

填充這是你如何讓你的預期的結果。