Ajax post请求将发送的数据附加到返回的JSON

时间:2016-11-09 19:05:49

标签: javascript php arrays json ajax

我有一个像这样的ajax调用:

$.ajax({
    url: '/assets/functions.php',
    type: 'POST',
    data: {
        "functionCall": "get-uploads",
        "type": type
    },
    dataType: 'json',
    success: function (data, textStatus) {
        console.log("done");
        console.log(data);
        console.log(textStatus);
    },
    error: function(textStatus, errorThrown) {
        console.log("uh oh");
        console.log(textStatus);
        console.log(errorThrown);
    }
});

通过以下方式发送和处理:

switch($_POST['functionCall']) {
    .
    .
    .
    case "get-uploads":

        $type = $_POST['type'];
        $getUploads = "SELECT * FROM pp_uploads WHERE type = '$type';";

        $docArray = array();

        while($row = mysql_fetch_assoc($documents)) {
            $docArray[] = $row;
        }

        echo json_encode($docsArray);
}

当我运行这个时,我得到一个解析错误,根据我的理解,这意味着返回的数据不会作为JSON返回。所以我将dataType更改为html,我看到控制台中返回的数据是:

[{"id":"35","filename":"fdgsdf","path":"ConfiguratorTreeDiagram.pdf","type":"resources"},{"id":"36","filename":"gsrewg","path":"dhx_advertising.pdf","type":"resources"}]Array
(
    [functionCall] => get-uploads
    [type] => resources
)

所以看起来我传入调用的数据被附加到我的数据末尾。我该如何防止这种情况发生?

1 个答案:

答案 0 :(得分:1)

看起来你可能在Array变量的某个地方做了一个print_r?