【问题标题】:Return Named Array in Ajax Request在 Ajax 请求中返回命名数组
【发布时间】:2015-11-24 11:50:51
【问题描述】:

我正在尝试传回一个带有命名索引的数组(例如:data.sugg_id)以用于发布请求。这就是我的 javascript / jQuery 的样子:

$.post('submit_text.php', JSON.stringify({'unit_id' : unit_id,
                                            'text' : text,
                                            'ignore_warnings' : ignore_warnings
                                            }), 
        function(data) {
            sugg_id = data.sugg_id;

            if (data.status == 'failure') {
                warning_history = {}
                showMessage(errorBox, data.message);
                warnBox.fadeOut("fast");
            }

我的 submit_text.php 看起来像:

<?
    header("Content-Type: application/json");

    $unit_id = $_POST["unit_id"];
    $text = $_POST["text"];
    $ignore_warnings = $_POST["ignore_warnings"];

    $sugg_id = 24;
    //$status = "success";
    $status = $text;
    $message = "";
    $data = array("sugg_id" => $sugg_id, "status" => $status, "message" => $message);
    echo json_encode($data);
?>

我尝试使用 alert(data.status) 但它显示“未定义”。我做错了什么?

【问题讨论】:

  • alert(data) 的输出是什么?如果它有数据,可能它仍然是 json 格式,所以你需要像 data = JSON.parse(data); 一样解析它。
  • 将数据类型json 传递给$.post() 方法
  • 您是否在 php 脚本中指定为 Content-Type: application/json
  • 你的控制台显示什么?

标签: javascript php jquery ajax


【解决方案1】:

正如@A 所建议的那样。沃尔夫传dataType

$.post('submit_text.php', JSON.stringify({'unit_id' : unit_id,
                                            'text' : text,
                                            'ignore_warnings' : ignore_warnings
                                            }), 
        function(data) {
            sugg_id = data.sugg_id;

            if (data.status == 'failure') {
                warning_history = {}
                showMessage(errorBox, data.message);
                warnBox.fadeOut("fast");
            }
}, "json");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-11
    • 2018-03-29
    • 2013-04-23
    • 2011-10-19
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多