【问题标题】:Trouble with converting json string in php array在 php 数组中转换 json 字符串时遇到问题
【发布时间】:2017-02-24 23:32:50
【问题描述】:

我想在 JavaScript 中发送一个 JSON 字符串,然后使用编码 php 函数将其转换为数组。

一旦使用 JavaScript 转换字符串并使用 Ajax 发送到 php 页面,我无法将其转换为数组。

这就是代码。

function goJsonAjaxPhp()
{
    var myObject ={name:"Andreas",surname:"Grech",age:20};
    var str_json = JSON.stringify(myObject);
    var xhr;
    if(window.XMLHttpRequest)
    {
        xhr = new XMLHttpRequest();
    }
    else
    {
        xhr = new ActiveXObject("Microsoft.HMLHTTP");
    }
    xhr.onreadystatechange = handler;
    xhr.open("POST","page_php.php",true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.send(str_json);
                                   
    function handler()
    {
        if(xhr.readyState == 4 && xhr.status == 200)
        {
            document.getElementById("idResult").innerHTML= xhr.responseText;
        }
    }
}
<button onclick=goJsonAjaxPhp()> Json Ajax-PHP </button>
<button onclick=goJsonPhp()> Json Only-PHP </button>
<button onclick=goJsonJavascript()> Json Javascript </button>

<div id=idResult></div>
header("Content-Type: application/json;ì");
$str_json = file_get_contents('php://input');
$arrayPHP = (array) json_encode($str_json,TRUE);
var_dump($arrayPHP);

这是php输出

我做错了什么?

【问题讨论】:

  • 你的 PHP 中肯定需要 json_decode...
  • 我已经试过了,但是没用
  • 请解释它是如何不起作用的。添加调试步骤。
  • 很遗憾我不知道如何检查调试步骤,对不起
  • 我解决了这个问题,你从一开始就是对的!非常感谢,请原谅

标签: javascript php arrays json ajax


【解决方案1】:

而不是

$arrayPHP = (array) json_encode($str_json,TRUE);

试试

$arrayPHP = (array) json_decode($str_json,TRUE);

【讨论】:

  • 你也可以去掉 (array) 转换,因为这是 true 在第二个参数中所做的。将其转换为数组还会阻止您查看它是否返回了 null,这意味着解码时出错。
  • 按照上面的建议进行调试,然后发布错误消息,以便我们识别可能的错误来源
猜你喜欢
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多