【发布时间】:2013-06-28 14:40:03
【问题描述】:
好的,这是我在阿贾克斯的第一次尝试,它让我发疯,因为我真的无法理解它。我想做的是用数据库中的客户填充第一个框,然后使用 customerID 使用 select.php 脚本从数据库中选择所有车辆 ID。 What is happening is the customers box is getting selected but when the select a customer nothing happens.
这是我的 Test.php 文件:
<?php include 'connectmysqli.php'; ?>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Select test</title>
<script src="./js/jquery/jquery.js"></script>
<script type="text/javascript" charset="utf-8">
$$('#customer')
.on('change', function () {
$.getJSON('select.php', { customerId: $(this)
.val() }, function (data) {
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x][
'id'] + '">' + data[x]['reg'] +
'</option>';
}
$('#vehicle')
.html(options);
});
});
</script>
</head>
<body>
<select id="customer">
<?php
$sql = <<<SQL
SELECT *
FROM `customers`
SQL;
if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']');}
while($row = $result->fetch_assoc()){
if ($row['bussinessname'] == ''){$name = $row['title'].' '.$name = $row['firstname'].' '.$name = $row['surname'];}else
{$name = $row['bussinessname'];}
echo '<option value="'.$row['customerID'].'">'.$name.'</option>';
}
echo '</select></p>'; ?>
</select>
<select id="vehicle">
</select>
</body>
</html>
这是我的 select.php 文件:
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['customerId'];
$sql = 'SELECT * FROM vehicles WHERE customerID = ' . $id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'id' => $row['vehicleID'],
'reg' => $row['reg'] // Don't you want the name?
);
}
echo json_encode($json);
?>
我正在尝试修改本教程以使用数据库,但到目前为止我没有成功。 http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/
在 Chrome 控制台中出现错误:
Port error: Could not establish connection. Receiving end does not exist. miscellaneous_bindings:235
chromeHidden.Port.dispatchOnDisconnect
【问题讨论】:
-
试试
$(document).on('change', "select#customer", function(){}); -
@Brewal 为什么会这样?
-
你能在控制台上检查一下,当项目被选中时是否建立了连接
-
我虽然你的
select#customer是动态添加的。这将修复错误。但这种情况并非如此。控制台有错误吗? -
可能你的 json 语法有误。尝试将您的数据添加到数组中,然后执行
echo json_encode($data); exit();
标签: javascript php jquery ajax