我有一个下拉菜单,使用onChange事件触发mysqli查询。查询用返回的结果填充一个数组,该数组又被赋值给$_SESSION变量。
我试图使用存储在$_SESSION变量中的数组来填充下拉菜单中的值更改时的选择框。
这是相关的JavaScript代码:
xmlhttp.open("POST", "getStudentList.php?q="+yearGroup, true);
xmlhttp.send();
var newStudentList =<?php echo json_encode($_SESSION['studentList']) ?>;
// clear select box
$('#studentList').empty();
// populate select box with JS array items
$.each(newStudentList, function(key, value) {
$('#studentList')
.append($('<option>', { value : key })
.text(value));
});
$('#studentList').selectmenu("refresh",true);
$_SESSION['studentList']在'getStudentList.php'中被正确更新,但更新没有反映在Javascript中的调用中,直到页面重新加载…如何使更新自动发生?
我检查了过去的帖子,但没有发现任何真正有帮助或我理解的东西!我将感激任何帮助-我是一个使用Javascript/Jquery的新手,并且已经从这里和那里拼凑了一些php,所以请对我宽容。(是的,我正在使用session_start()!)
提前感谢!
你可以这样做,
$("#studentList").on('change',function() {
$.ajax({
url: "getStudentList.php",
dataType: "json",
success: function(newStudentList) {
// clear select box
$('#studentList').empty();
// populate select box with JS array items
$.each(newStudentList, function(key, value) {
$('#studentList').append($('<option>', { value : key }).text(value));
});
$('#studentList').selectmenu("refresh",true);
}
});
});
PHP代码仅在生成HTML页面的源代码时运行。一旦浏览器运行了JS代码,PHP就已经运行了,你的echo
就产生了一串字符,就像你手工输入的一样。
为了运行更多的PHP代码,您需要从服务器获取一个新文件。这是AJAX背后的基本概念:你写一个JS函数,它向服务器请求一个新页面,通常包含XML或JSON,但其他方面就像任何网页一样。但是,JS回调函数不会显示新页面,而是读取它并对其进行处理。