简体   繁体   中英

How to parse my JSON string into a multidimensional array in Javascript after passing JSON string from php file with AJAX?

I am doing some testing before I run a full scale program, and good thing I am. I have been doing some tests to return a multidimensional array from my php file to my htm webpage. I have tested many things to narrow my issue down to JSON.parse(). Here is my PHP code in file response.php:

<html>
<head>
</head>

<body>
<?php
$test = array(
array("first" => "Aaron", "last" => "Rodgers"),
array("first" => "Willie", "last" => "Makit")
);
//header('Content-Type: application/json');
echo json_encode($test);
?>
</body>
</html>

and my output is normal:

{"0":{"first":"Aaron","last":"Rodgers"},"1":{"first":"Willie","last":"Makit"}} //New output as per object typecasting

Then on my htm file I am just trying to display the first name "Aaron" as an output after my button press. here is the code for my html and javascript:

<html>
<head>
<script type="text/javascript" language="javascript">
function ajaxTest(){
    var testAjax = new XMLHttpRequest();
    testAjax.onreadystatechange = function(){
        if(testAjax.readyState==4)
        {
            var test1 = JSON.parse(testAjax.responseText);
            document.getElementById("doIt").innerHTML = test1.row[0].first;    //I believe my error might be an issue with my formatting on this line
        }
    }
    testAjax.open("GET", "response.php", true);
    testAjax.send(null);
}
</script>
</head>

<body>
<input type="button" value="try it" onclick="ajaxTest()"/>
<div id="doIt"></div>
</body>
</html>

I have tried displaying the raw json string and that works. But once I use JSON.parse() any data I try to display is blank. I have tried several formats including the following:

document.getElementById("doIt").innerHTML = test[0][1];
... = test[0].first;
... = test;
... = test.length;

But regardless of the format I get no output (that is visible at least). The part that puzzles me is that even my array.length will not display a value. I get no error messages, just a blank output. Thanks in advance for any pointers or fixes everyone.

edit: after type casting my outer array as an object I still only get blank outputs. I do however think typecasting was necessary in my case.

In the PHP file, remove the HTML tags. That will solve the problem. Otherwise when responseText is called from the .htm file the string will include the HTML tags and will cause a syntax error when the data is parsed with JSON.parse().

This is not an answer to your question - you've already solved the problem. But I wanted to follow up on a couple of comments, and an answer is the only way to do proper code formatting.

@hyphenbash made an excellent suggestion: wrap your array inside an object for the JSON output, instead of outputting the bare array. While JSON does allow an array at the top level (contrary to the comment that said this would be invalid JSON), there are advantages to using an object instead and putting the array as a property inside the object.

Consider the array version of your original JSON (before the (object) cast was added). It looked like this (with some formatting for readability):

[
    { "first":"Aaron", "last":"Rodgers" },
    { "first":"Willie", "last":"Makit" }
]

There is nothing wrong with that, but suppose you want to add something else to the JSON response that is not part of the array, perhaps some kind of status or error indication. There is no place to put it!

By contrast, suppose you wrapped the array in an object instead:

{
    data: [
        { "first":"Aaron", "last":"Rodgers" },
        { "first":"Willie", "last":"Makit" }
    ]
}

Now if you want to add some other bit of information it's easy:

{
    status: "test",
    data: [
        { "first":"Aaron", "last":"Rodgers" },
        { "first":"Willie", "last":"Makit" }
    ]
}

The PHP code to generate this is a simple change from your original:

<?php
$test = array(
    "status" => "test",
    "data" => array(
        array("first" => "Aaron", "last" => "Rodgers"),
        array("first" => "Willie", "last" => "Makit")
    )
);
echo json_encode($test);
?>

And it's equally easy to handle this in your JavaScript code:

var test1 = JSON.parse(testAjax.responseText);
document.getElementById("doIt").innerHTML = test1.data[0].first;

Note a couple of other little changes here that I recommend in JavaScript code:

  • Take out the quotes around the 0 - either will work, but it's customary to use numeric indices with an array.

  • Use .foo notation instead of ["foo"] when accessing object properties. Either one works here too, but .foo is customary and more concise.

It is somewhat confusing to switch between PHP and JavaScript, since JavaScript has separate concepts of arrays and objects, where PHP combines them both into one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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