好的,这是我对Ajax的第一次尝试,它使我发疯,因为我实在无法绕开它。我想做的是在第一个框中用数据库中的客户填充,然后使用customerID通过select.php脚本从数据库中选择所有车辆ID。发生的情况是“客户”框被选中,但是选择客户时什么也没有发生。
这是我的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.ready:
<script type="text/javascript" charset="utf-8"> $(document).ready(function(){ $('#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>
我也改为$$('#customer')了$('#customer')。最后,修复您的SQL注入漏洞:
$$('#customer')
$('#customer')
$sql = 'SELECT * FROM vehicles WHERE customerID = ' . (int)$id;
在此处将ID强制转换为int会阻止SQLi,但是您应该考虑使用Prepared Statement。
您在问题中提到的错误看起来与您的代码无关。它看起来与Chrome扩展程序有关。
这不是问题的一部分,但这是构建车辆选项的代码的改进版本:
$.getJSON('select.php', {customerId: $(this).val()}, function(data){ var vehicle = $('#vehicle'); for (var x = 0; x < data.length; x++) { vehicle.append(new Option(data[x].reg, data[x].id)); } });
改进之处包括:
new Option(...)
.append()
<
>
data[x].id
data[x]['id']