2010-09-07 58 views
1

我有一個表單,其中包含一個名爲Client_ID的選擇以及一些其他文本輸入。我需要的是,當用戶選擇CLIENT_ID,我的領域地址1,地址2等應與沿jquery根據選擇值從表中填充文本輸入

SELECT Address1, Address2 from Client where Client_ID = Client_ID 

行數據庫查詢的結果填充我知道這是一個小白有點問題,但真的很感謝一些最簡單和最好的方法來幫助做到這一點。

回答

2

你應該做這樣的事情與jQuery + JSON

首先從here所有下載的jQuery的,包括它在你的應用程序。

如果home.php,你下載的jQuery文件(jQuery的1.4.2.min.js)和訪問getdata.php在同一個文件夾,然後您home.php會看起來像這樣的:

home.php(文件包含您的形式)

<html> 

<head> 

    <script type="text/javascript" src="jquery-1.4.2.min.js"></script> 

    <script type="text/javascript"> 
    jQuery(document).ready(function(){ 
     jQuery('#Client_ID').live('change', function(event) { 
      $.ajax({ 
       url  : 'getData.php', 
       type : 'POST', 
       dataType: 'json', 
       data : $('#myform').serialize(), 
       success: function(data) { 
         for(var id in data) {   
           $(id).val(data[id]); 
         } 
       } 
      }); 
     }); 
    }); 
    </script> 

</head> 

<body> 

    <form id='myform'> 
    <select name='Client_ID' id='Client_ID'> 
     <option value=''>Select</option> 
     <option value='1'>Client 1</option> 
     <option value='2'>Client 2</option> 
    </select> 

    <input type='text' name='address1' id='address1'> 
    <input type='text' name='address2' id='address2'> 

    <select name='gender' id='gender'> 
     <option value=''>Select</option> 
     <option value='1'>Male</option> 
     <option value='2'>Female</option> 
    </select> 

    </form> 

</body> 


</html> 

訪問getdata.php

<?php 

$clientId = $_POST['Client_ID']; // Selected Client Id 

$query = "SELECT Address1, Address2 from Client where Client_ID = $clientId"; 
$result = mysql_query($query); 
$row = mysql_fetch_array($result, MYSQL_ASSOC) 

$add1 = $row[Address1]; 
$add2 = $row[Address2]; 
$gender = 1; 

$arr = array('input#address1' => $add1, 'input#address2' => $add2, 'select#gender' => $gender); 
echo json_encode($arr); 

?> 

我已經在我的機器上測試過這段代碼,它正在工作。

+0

(+1)雖然我總是發現如果我打算在客戶端處理動態字符串,從服務器返回json是最安全的。 – Bob 2010-09-07 09:36:15

+0

使用你的方法,我回過頭來看看getdata.php中有效的數據,如果我在瀏覽器中調用頁面的話。但是,更改選擇的值時沒有任何事情發生。我是否正確使用jquery代碼,將其放置在頁面的頭部部分中? – Istari 2010-09-07 13:16:09

+0

如果選擇更改事件沒有發生,那麼這意味着您的jQuery代碼沒有正確包含或者您的jQuery庫不包含在內。是的,您可以在頭部添加jquery代碼,但必須在''標籤中關閉它,並使用ready功能。看看編輯答案。 jquery代碼現在添加在頭部分中。仔細閱讀整個答案,然後重試。如果不成功,請再次報告,我會盡力幫忙。 – NAVEED 2010-09-08 02:26:12

1

閱讀this tutorial。我認爲它可以幫助您理解將數據從客戶端移動到服務器的概念,反之亦然。

請記住,在你的情況下,你需要結合事件。

$(document).ready(function(){ 
    $("#my_select_box").change(function() 
    { 
     //send the data to the server as in the tutorial above 
    }); 
}); 
相關問題