简体   繁体   English

使用AJAX从php文件传递JSON字符串后,如何将JSON字符串解析为Javascript中的多维数组?

[英]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. 我一直在做一些测试,以将多维数组从我的php文件返回到我的htm网页。 I have tested many things to narrow my issue down to JSON.parse(). 我已经测试了许多方法,将问题缩小到JSON.parse()。 Here is my PHP code in file response.php: 这是我在文件response.php中的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. 然后在我的htm文件中,我只是想在按下按钮后将名字“ Aaron”显示为输出。 here is the code for my html and javascript: 这是我的html和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. 我尝试显示原始的json字符串,并且有效。 But once I use JSON.parse() any data I try to display is blank. 但是一旦我使用JSON.parse(),我尝试显示的任何数据都是空白。 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. 令我感到困惑的部分是,即使我的array.length也不会显示值。 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. 在PHP文件中,删除HTML标记。 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(). 否则,当从.htm文件中调用responseText时,该字符串将包含HTML标记,并且在使用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. @hyphenbash提出了一个很好的建议:将数组包装在一个对象中以进行JSON输出,而不是输出裸数组。 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. 尽管JSON确实允许在最高级别使用数组(与声明这将是无效JSON的注释相反),但使用对象代替并将数组作为属性放入对象内部有很多好处。

Consider the array version of your original JSON (before the (object) cast was added). 考虑原始JSON的数组版本(在添加(object)强制类型转换之前)。 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. 没什么问题,但是假设您想向JSON响应中添加属于数组的其他内容,可能是某种状态或错误指示。 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代码是对原始代码的简单更改:

<?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: 在您的JavaScript代码中同样容易处理:

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: 请注意我在JavaScript代码中建议的其他一些小更改:

  • Take out the quotes around the 0 - either will work, but it's customary to use numeric indices with an array. 删除0左右的引号-都可以,但是习惯上将数字索引与数组一起使用。

  • Use .foo notation instead of ["foo"] when accessing object properties. 访问对象属性时,请使用.foo表示法代替["foo"] Either one works here too, but .foo is customary and more concise. 两种方法也都可以在这里使用,但是.foo是惯用的,而且更加简洁。

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. 在PHP和JavaScript之间进行切换有些令人困惑,因为JavaScript具有数组和对象的独立概念,其中PHP将数组和对象结合在一起。

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

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