drllqg2903 2015-11-24 11:50
浏览 27
已采纳

在Ajax请求中返回命名数组

I am trying to pass back an array with named indexes (e. g.: data.sugg_id) for a post request. This is how my javascript / jQuery looks like:

$.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");
            }

My submit_text.php looks like:

<?
    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);
?>

I tried to use alert(data.status) but it said "undefined". What am I doing wrong?

  • 写回答

1条回答 默认 最新

  • dongyingdao8867 2015-11-24 12:01
    关注

    As suggested by @A. Wolff pass 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");
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号