JSON.stringify发送空对象

时间:2016-02-12 02:14:12

标签: javascript php json ajax

我决定停止使用jQuery,因此我将所有内容都转换为纯JavaScript。

我有ajax调用,我想将网址的最后一部分发送到php服务器,但JSON.stringify()在服务器中发送empty object

为什么会这样?

AJAX电话:

var ajax = new XMLHttpRequest();

ajax.open('get', 'ajax/autocomplete.php');
ajax.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
ajax.send(JSON.stringify({q: document.location.href.split('/').slice(-1)[0]}));

PHP:

<?php
    require_once '../../private/core/init.php';
    header('Content-Type: application/json');

    print_r($_GET);//empty

    $data = new AUTOCOMPLETE($_GET['q']);
    echo json_encode($data->data());
?>

我收到此错误:Undefined index: q

1 个答案:

答案 0 :(得分:1)

您可能希望使用error_reporting(0)来抑制PHP错误;或者首先使用isset / empty验证输入数据,或者使用其他一些函数来抑制PHP警告。警告输出将使您的JSON响应数据对您的javascript(jQuery或纯javascript)无效。

<?php
error_reporting(0);
require_once '../../private/core/init.php';
header('Content-Type: application/json');

if (isset($_GET['q'])) {
    $data = new AUTOCOMPLETE($_GET['q']);
    echo json_encode($data->data());
}
?>
相关问题