简体   繁体   中英

How to use JSON data (array) from PHP in Javascript

I would like to retrieve each element inside of this.responseText , and put them in my HTML on Javascript. Is there something wrong in my code? I hope my code helps you to understand my question. Thanks. (ps the html code is provided, and so I cannot use jquery.)

an example of this.responseText is below; (By using alert , I got that)

{"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."}

And my java script is below;

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);
    }
}

or is there something wrong in my PHP code??

$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));
    }
}

This doesnt look like valid JSON, should be like '[{},{},{}]'. If you want you can use a JSON validator, eg http://json-validator.com/ .

To generate the JSON array properly you can do:

$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));

Simple use this exemple for 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
));

In this example you define, that you are using Json with this line of code:

datatype = "Json";

In your php you send back the data through:

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

To use the data in your ajax:

response.nunber_of_rows

The example it's from this link How to use Ajax and JSON for making dropdown menu?

If you do not want to use 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]);
    }

To get the php array you need only to do this:

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

The example it's from this link Pass a PHP array to a JavaScript function

To use JSON.parse:

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

Example:

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>

Now to get a value from your original array, you just have to use:

books[1].author

The example it's from this link http://www.dyn-web.com/tutorials/php-js/json/parse.php

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