好的,所以我已经有2天尝试这样做,但由于某种原因,无论我做什么方式都没关系,它不起作用(我尝试了不同的方式与json_encode,然后照顾创建使用javascript的元素,我试图在php本身回应,我试图返回它,没有什么真正有用的)
我要做的是使用AJAX向服务器询问特定脚本(现在是test.php),然后返回<option>
,这样我就可以填充<select>
,所以我试图填充一个comboBox,似乎正在发生的事情是AJAX响应是空的,我试图输出结果,它输出一个空值。任何人都可以帮助我,我真的很绝望,这应该很容易,我花了几个小时在堆栈溢出试图找到问题,我已经调试了代码,我尽我所能,我'我已经阅读了jquery文档中的所有相关内容。好吧无论如何我把我的痛苦放在一边,这是代码:
comboStaging.php:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form id="testForm">
<select name="states" id="states">
<?php
$odb = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "SELECT id, name FROM `database`.pt_state";
$data = $odb->prepare($query);
$data->execute();
while ($row = $data->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="' . $row['id'] . '">' . $row['name'] . '</option>';
//print_r($row);
}
?>
</select>
<select name="cities" id="cities">
</select>
</form>
<script type="text/javascript">
$(document).ready(function () {
console.warn("test");
function loadFirst() {
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data: "id=1",
dataType: "html",
success: function (data) {
console.warn("test2")
console.warn(data);
}
});
}
console.warn("test3");
loadFirst();
});
$("#states").change(function () {
var ID = document.getElementById("states").valueOf().value;
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data: "id=" + ID,
success: function (r) {
document.getElementById("cities").innerHTML = r;
}
});
});
</script>
</body>
</html>
test.php的:
<?php
header('Content-Type: text/html');
require_once $_SERVER['DOCUMENT_ROOT'] . "/resources/scripts/php/conn/dal.php";
$stmt = $DB_con->prepare('SELECT id, name FROM `database`.pt_city WHERE state_id=:state');
$stmt->bindParam(':state', $_GET['ID']);
$stmt->execute();
if($stmt->rowCount() > 0 ) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$test = $test . '<option value="' . $row['id'] . '"id="optionTest">' . $row['name'] . '</option>';
}
}
return $test;
?>
开发控制台: branch protection settings