如何在Javascript中使用PHP中的JSON数据(数组)

时间:2017-05-20 07:20:13

标签: javascript php json

我想检索this.responseText内的每个元素,并将它们放在我的HTML上的Javascript中。我的代码中有什么问题吗?我希望我的代码可以帮助您理解我的问题。谢谢。 (p.s.提供了html代码,所以我不能使用jquery。)

下面是this.responseText的示例; (通过使用alert,我得到了)

{"name":"Hermione Grainger","number":"4","review":"Not as good as the NEXT book in the series, but hilarious and satisfying."}{"name":"Ronald Drumpf","number":"1","review":"Feminist propaganda!"}{"name":"Brienne of Tarth","number":"5","review":"Alanna is my best friend."}

我的java脚本在下面;

function bookReview(){
    var reviews = JSON.parse(this.responseText);
    for(var i=0; i<reviews.length; i++){
        var name = document.createElement("h3");
        var text = document.createElement("p");
        name.innerHTML = reviews[i].name + reviews[i].number;
        text.innerHTML = reviews[i].review;

        document.getElementById("reviews").appendChild(name);
        document.getElementById("reviews").appendChild(text);
    }
}

或者我的PHP代码有什么问题吗?

$path = "books/$book/";
review(glob($path . "review" . "*" . ".txt"));

function review($reviews) {
    foreach ($reviews as $each) {
        $review = file($each, FILE_IGNORE_NEW_LINES);
        $output = array (
            "name" => $review[0],
            "number" => $review[1],
            "review" => $review[2]
            );
        header("Content-type: application/json");
        print(json_encode($output));
    }
}

2 个答案:

答案 0 :(得分:1)

这看起来不像有效的JSON,应该像'[{},{},{}]'。如果您愿意,可以使用JSON验证器,例如: http://json-validator.com/

要正确生成JSON数组,您可以执行以下操作:

$array = [];
foreach ($reviews as $each) {
    $review = file($each, FILE_IGNORE_NEW_LINES);
    $output = array (
        "name" => $review[0],
        "number" => $review[1],
        "review" => $review[2]
        );
    array_push($array,$review);
}
print(json_encode($array));

答案 1 :(得分:0)

简单地使用这个例子来表示ajax:

AJAX:

 $.ajax({
        url: 'test.php',
        type: 'POST',
        datatype: 'Json',
        data: {'q': val_1},
        success: function (response) {
           var newhref;
           var newhrefid;
           var div=document.getElementById("myDropdown"); 
           for(var i = 0; i<response.nunber_of_rows; i++){
             newhref= document.createElement("a");
             newhref.href= response.tabel[i];
             newhref.innerHTML= response.tabel[i];
             newhrefid = "idhr_"+i;
             newhref.setAttribute('id', newhrefid );
             div.appendChild(newhref);
           } 
        }
    });

PHP:

...//your code
echo json_encode (array(
                    'tabel'=>$tabel,
                    'nunber_of_rows'=>$nunber_of_rows
));

在这个例子中,你定义了你正在使用这行代码的Json:

datatype = "Json";

在你的php中,你通过以下方式发回数据:

echo json_encode (array(
                    'tabel'=>$tabel,
                    'nunber_of_rows'=>$nunber_of_rows
));

使用ajax中的数据:

response.nunber_of_rows

此链接中的示例How to use Ajax and JSON for making dropdown menu?

如果您不想使用AJAX:

PHP:

$phpArray = array(
          0 => "Mon", 
          1 => "Tue", 
          2 => "Wed", 
          3 => "Thu",
          4 => "Fri", 
          5 => "Sat",
          6 => "Sun",

    )

JS:

    var jArray= <?php echo json_encode($phpArray ); ?>;

    for(var i=0;i<6;i++){
        alert(jArray[i]);
    }

要获取php数组,您只需执行此操作:

var jArray= <?php echo json_encode($phpArray ); ?>;

此链接中的示例Pass a PHP array to a JavaScript function

使用JSON.parse:

var data = JSON.parse( '<?php echo json_encode($data) ?>' );

示例:

PHP:

<?php
$books = array(
    array(
        "title" => "Professional JavaScript",
        "author" => "Nicholas C. Zakas"
    ),
    array(
        "title" => "JavaScript: The Definitive Guide",
        "author" => "David Flanagan"
    ),
    array(
        "title" => "High Performance JavaScript",
        "author" => "Nicholas C. Zakas"
    )
);
?>

JS:

<script type="text/javascript">
// using JSON.parse on the output of json_encode
var books = JSON.parse( '<?php echo json_encode($books); ?>' );

/* output (with some whitespace added for readability)
[
    {"title":"Professional JavaScript", "author":"Nicholas C. Zakas"},
    {"title":"JavaScript: The Definitive Guide", "author":"David Flanagan"},
    {"title":"High Performance JavaScript", "author":"Nicholas C. Zakas"}
]
*/

// how to access
console.log( books[1].author ); // David Flanagan
</script>

现在要从原始数组中获取值,您只需使用:

books[1].author

此链接中的示例http://www.dyn-web.com/tutorials/php-js/json/parse.php