【问题标题】:How to use JSON data (array) from PHP in Javascript如何在 Javascript 中使用来自 PHP 的 JSON 数据(数组)
【发布时间】:2017-10-20 08:28:10
【问题描述】:

我想检索this.responseText 中的每个元素,然后将它们放入我在Javascript 上的HTML 中。我的代码有问题吗?我希望我的代码可以帮助您理解我的问题。谢谢。 (ps提供了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));
    }
}

【问题讨论】:

    标签: javascript php json


    【解决方案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));
    

    【讨论】:

    • 我添加了我的 PHP 代码。请检查我的 PHP 代码好吗?
    • 在此处查看第二个答案:stackoverflow.com/questions/6739871/…(在循环中生成数组,然后在循环之外将它们放入数组中并 json.encode 这个)。
    • 我把它改成下面的代码,但是效果不好... function review($reviews) { foreach ($reviews as $each) { $review = file($each, FILE_IGNORE_NEW_LINES ); $output = array ( array( "name" => $review[0], "number" => $review[1], "review" => $review[2] ) ); } header("内容类型:应用程序/json");打印(json_encode($输出)); }
    • 每个 $output = array (...);在循环中只生成一个数据结构,您必须将它们全部放在一个数组中(请参阅我的编辑)。此外,$output 仅在它声明的块中可用(也就是 for 循环的内部),或者至少我猜 php 以这种方式处理它。
    • 非常感谢!我能理解!
    【解决方案2】:

    简单地用这个例子来做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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-26
      • 2021-10-25
      • 2013-11-29
      • 2011-04-27
      • 1970-01-01
      • 2012-06-29
      • 2018-06-24
      • 1970-01-01
      相关资源
      最近更新 更多