【问题标题】:PHP/JSON encodingPHP/JSON 编码
【发布时间】:2013-12-18 20:32:11
【问题描述】:

我正在使用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,但没有运气。我做错了什么?

【问题讨论】:

  • 您的代码容易受到 SQL 注入的影响,并且将来会成为问题 - 无论是有意还是无意。 永远不要相信用户变量。查看bobby-tables.com
  • 使用mysqli 时,您应该使用参数化查询和bind_param 将用户数据添加到您的查询中。 避免使用字符串插值来完成此操作。
  • 顺便说一句,如果 course_cost 只是一个数值,你可以跳过 json_encode
  • @nl-x 试过了,还是不行
  • @h2ooooooo 使用准备好的语句与使用 mysqli_real_escape_string 过滤 POST 变量相比如何?

标签: php jquery mysql ajax json


【解决方案1】:

在你的第二个 Ajax 中你写 date 而不是 data

编辑:

此外,使用浏览器的 Element Inspector 并查看:

  • “网络”选项卡在 Ajax 调用期间发生了什么。查看数据是否确实正在发送。以及网络服务器返回的内容。
  • 控制台选项卡查看您是否收到任何 javascript 消息/错误

【讨论】:

  • 好眼光。这确实是问题所在。但也许 ElendilTheTall 还需要一些服务器端验证来解决此类错误。
  • 是的,您确实...查看您发布的您自己的代码。 datE: event_selected,
  • @ElendilTheTall :是的,你这样做
  • 现在请修复你的 sql 注入问题,正如 h2ooooo 所说:)
  • 知道了 - mysqli_fetch_field 需要 1 个参数。我删除了MYSQLI_ASSOC,它可以工作。谢谢!
猜你喜欢
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2012-05-11
  • 2016-08-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多