简体   繁体   English

json_decode() 返回 null 而不是一个数组

[英]json_decode() returns null instead an array

I am going to INSERT an array of objects into mysql via AJAX but on server side json_decode() returns null我将通过 AJAX 将对象数组插入 mysql 但在服务器端json_decode()返回null

How can i solve this?我该如何解决这个问题?

This is the ajax codes:这是 ajax 代码:

let mainObj = [

    { username: 'david', password: 33456, email: 'david@gmail.com' },
    { username: 'rose', password: 3333, email: 'rose@gmail.com' },
    { username: 'adam', password: 95112, email: 'adam@gmail.com' },
    { username: 'lisa', password: 'sarlak', email: 'lisa@gmail.com' },

]



let sendMe = JSON.stringify(mainObj);



let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {

    if (this.readyState == 4 && this.status == 200) {


        document.getElementById('result').innerHTML = xhr.responseText;
    }


}

xhr.open("GET", "check.php?x=" + sendMe, true);
xhr.send();



And the php codes (check.php): php 代码(check.php):

$obj= json_decode($_GET['x'], true);

$b= $obj[1]->username;


var_dump($b);

It returns null but i need it returns an array of objects which be usable in database.它返回null但我需要它返回可在数据库中使用的对象数组。

You are trying to treat an array as an object, json_decode returns an array not an object or stdclass... instead of您正在尝试将数组视为 object, json_decode返回的数组不是 object 或 stdclass... 而不是

$b= $obj[1]->username;

should be应该

$b= $obj[1]['username'];

I'm assuming that you are not using any framework since the thing that you did should throw and exception so it's better to enable error reporting我假设您没有使用任何框架,因为您所做的事情应该抛出和异常,因此最好启用错误报告

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

Since you're using the second parameter true in $obj= json_decode($_GET['x'], true);由于您在$obj= json_decode($_GET['x'], true);中使用第二个参数true your returned $obj will be an array.您返回的$obj将是一个数组。 You either use:你要么使用:

$obj = json_decode($_GET['x']);
$b = $obj[1]->username;

or或者

$obj = json_decode($_GET['x'], true);
$b = $obj[1]['username'];

to get "rose".得到“玫瑰”。

https://www.php.net/manual/en/function.json-decode.php https://www.php.net/manual/en/function.json-decode.php

Something like this (others already wrote it..):像这样的东西(其他人已经写了..):

$json = '[{"username":"david","password":33456,"email":"david@gmail.com"},{"username":"rose","password":3333,"email":"rose@gmail.com"},{"username":"adam","password":95112,"email":"adam@gmail.com"},{"username":"lisa","password":"sarlak","email":"lisa@gmail.com"}]';

$decodedJson = json_decode($json, true);


// $b= $decodedJson[1]->username; // Wrong, you have an array, not object
// Correct
foreach($decodedJson as $single) {
    print_r($single["username"]."\n");
}

// Prints out: // 打印出来:

david rose adam lisa

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM