我想从MYSQL数据库中获取我的客户电话号码,并根据用户在先前下拉框中选择的客户将其自动填充到输入框中。
我过去在填写大量数据时设法做到这一点,但我以前使用的似乎是很多代码来自动填充单个输入框。
我知道如何根据从上一页传递的数据填充客户电话(尽管我在此处删除了该位),但我希望该数据在用户使用下拉列表时动态更改。
必须有一个简单的方法来做到这一点,但我是js的新手(并且勉强精通PHP和MYSQL)。谁能帮我一把?
我的 PHP/HTML:
$result = mysql_query("SELECT cust_id, name, phone FROM customers ORDER BY name ASC");
$customers = mysql_fetch_array($result);
<label for="customer">Customer:</label>
<select name="customer">
<option value="0">Add New Customer</option>
<? foreach ($customers as $customer): ?>
<option value="<?=$customer['cust_id']?>" <?=($customer['cust_id'] == $parts['cust']) ? "selected" : ""?>><?=$customer['name']?></option>
<? endforeach; ?>
</select>
<label for="custphone">Customer Phone:</label>
<input type="text" name="custphone" value="">
如果您需要我提供任何其他信息,请告诉我,并提前感谢您对此的帮助。
对于这个答案,我将使用 jQuery 语法,jQuery 是一个免费的 JavaScript 库,你以后肯定会使用它,阅读更多.
为了恢复,我们将使用由您的 select
元素触发的事件,当他的值更改时,我们将处理一个带有一些参数的 AJAX 请求到 PHP 页面 (ajax.php),该页面返回之前选择的客户电话号码。
首先,您需要在HTML网页中包含jQuery脚本,并带有<script>
标签.
<script src="path/to/jquery.js"></script>
第二次,我们将创建一个新的 javascript 脚本(假设你在 HTML 元素中添加了一些 id):
<script type="text/javascript">
$(document).ready(function(){ // When the document is ready
$("select#customers").on("change",function(){ // We attach the event onchange to the select element
var customer_id = this.value; // We retirve the customer's id
$.ajax({
url : "path/to/ajax.php", // path to you php file which returns the phone number
method : "post", // We want a POST request
data : "customer_id="+customer_id, // You'll retrieve this data in your $_POST variable in ajax.php : $_POST['customer_id']
success: function(response) { // The function to execute if the request is a -success-, response will be the customer phone number
$("input#custphone").value(response); // Fill the phone number input
}
});
});
});
</script>
现在,您已经准备好继续工作了,您应该阅读有关jQuery和AJAX的信息。您只需要创建"ajax.php",使用 $_POST
变量检索您的客户 ID,处理 SQL 查询以检索电话号码,然后返回带有 echo
的 。
听起来你想研究一下AJAX。 jQuery.ajax()
使它变得非常容易。
基本上,你在服务器上有一个页面,它查询数据库并返回一个JSON编码的字符串,javascript可以将其转换(使用jQuery.parseJSON
)转换回数组并填充列表!
使用 .change()
将事件绑定到下拉列表的更改事件。每当选择更改时,这将触发。在内部,您希望获取值(请参阅该页面上的演示)并向服务器发送 AJAX 请求。
服务器上的 PHP 脚本将查询数据库并返回 JSON 字符串。在 jQuery AJAX 块的success
函数中,您可以使用解码的信息填充新列表。有关如何将项目添加到选择的教程,请参阅此页面。