【问题标题】:Cannot read NULL variable in PHP after posting JSON array through .ajax()通过 .ajax() 发布 JSON 数组后无法读取 PHP 中的 NULL 变量
【发布时间】:2019-05-20 23:43:55
【问题描述】:

我和许多其他人一样遇到问题,在通过 ajax() 发送后能够读取 PHP 数组变量。 Ajax 成功并显示返回的数据,即 NULL。我已经彻底研究了这个 JSON/PHP 问题的 SO 解决方案,并且我的问题描述显示了迄今为止关于 SO 的“几乎”每个解决方案。

在我尝试过的 PHP 方面:

$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);

(跳过 $HTTP_RAW_POST_DATA(已弃用),因为它等于 file_get_contents('php://input')

还有:

$data = json_decode($_POST["a_arr"], true);

我已经尝试使用 sed 命令清除 UTF-8 BOM

sed '1s/^\xEF\xBB\xBF//' < index.html > index2.html

我的 .ajax() 看起来像这样:

$.ajax ({
    url:"file.php",
    method:"post",
    contentType: "application/json; charset=utf-8",
    data: { a_arr : JSON.stringify(arr) },
    })
    .done(function(response){
        $("#status").html(response);
    });

在 Javascript 方面,这是我的数组:

var arr = [{"name":_name, "phone":_phone, "email":_email, "repname":repname, "repnumber":repnumber, "office":office}];
ajax_post(arr);

我已检查以确保没有 JSON 格式错误,以下成功显示了一个有效的 JSON 格式数组:

var data_arr = JSON.stringify(arr);
document.getElementById("status").innerHTML = data_arr;

【问题讨论】:

  • 我已经彻底审查了类似 JSON/PHP 案例的 SO,虽然看起来很接近,但我没有找到我的问题描述所示的解决方案。

标签: javascript php json ajax jsonencoder


【解决方案1】:

你需要改成:

data: JSON.stringify(arr),

当您将对象提供给 data: 选项时,它会将其转换为 URL 编码格式,而不是 JSON。

或者你可以保留 data: 选项,但去掉 contentType: 选项,然后你应该使用

$data = json_decode($_POST['a_arr'], true);

【讨论】:

  • 非常感谢您的输入和信息!好的,我尝试了您的建议,依靠数据:推送URL编码,我删除了名称并放入:数据:JSON.stringify(arr),这也返回NULL!然后我把 data: 元素改回 JSON 格式:data: { a_arr : JSON.stringify(arr) },注释掉 contentType: //contentType: "application/json; charset=utf-8",最后从php://输入到:$data = json_decode($_POST['a_arr'], true); $var_dump($data);在这两种情况下仍然是 NULL :(
  • 您使用的是什么版本的 jQuery? method: 选项是在 1.9.0 中添加的,在此之前它是 type:
  • 你在var_dump(file_get_contents("php://input"));看到了什么?
  • 使用:jquery-1.8.3.min.js
  • 哇,好建议:返回数据是:string(0) "" 这很有趣,因为我得到了一个有效的 javascript JSON 字符串 pre .ajax()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-22
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 2018-03-12
  • 1970-01-01
相关资源
最近更新 更多