我正在使用 this answer 中的技术用 MySQL 条目填充下拉列表。 。这工作正常 - 当我选择一个事件时,会生成一个新的下拉列表,其中包含该事件运行的日期。
但是,我还需要从数据库中检索事件的成本,并将其分配为表单输入的值。最简单的方法是将其分配给事件下拉列表的 value 属性,但这已用于生成第二个下拉列表。
因此,我想我可以在事件下拉列表的 change
事件中使用另一个 Ajax 调用来再次查询数据库并获取成本,然后将其作为 JSON 编码变量传回。这是我的 Ajax 调用:
$('#event_menu').on('change', function() {
// get selected value and build data string for AJAX
var event_selected = "event_selected="+$(this).val();
// send the selected data to a PHP page to build the populated menu
$.ajax({
url : 'populate_menu.php',
type: 'POST',
data : event_selected,
dataType : 'html',
success : function(data) {
$('#instancemenu').html(data);
}, error : function() {
alert("Something went wrong!");
}
});
$.ajax({
url : 'get_eventprice.php',
type: 'POST',
date: event_selected,
dataType : 'json',
success : function(data){
$('#totalcost').val(data);
}, error : function(){
alert("Something went wrong with the price setter!")
}
});
});
这是 get_eventprice.php
中的代码:
$event_selected = isset($_POST['event_selected']) ? $_POST['event_selected'] : null;
$q="SELECT event_cost FROM events WHERE event_id=$event_selected";
$r=mysqli_query($dbc,$q);
$row=mysqli_fetch_field($r, MYSQLI_ASSOC);
echo json_encode($row['course_cost']);
但是,这会触发 Ajax 调用中的错误子句。我也尝试过 mysqli_fetch_array ,但没有运气。我做错了什么?
最佳答案
在第二个 Ajax 中,您编写 date
而不是 data
编辑:
此外,使用浏览器的元素检查器,然后查看:
- 网络选项卡在 Ajax 调用期间发生了什么。查看数据是否确实正在发送。以及网络服务器返回的内容。
- “控制台”选项卡可查看您是否收到任何 JavaScript 消息/错误
关于PHP/JSON 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20667821/