【问题标题】:Javascript cannot process JSON text fileJavascript 无法处理 JSON 文本文件
【发布时间】:2015-03-09 22:07:48
【问题描述】:

我正在按照一些教程从服务器传递一个 JSON 文本文件,以在对 html 文件进行一些 javascript 处理后显示数据。作为测试,尝试显示一列的 LI,但无法在浏览器中获得任何输出。感谢您的帮助。

我尝试了两种方法。

方法一 xmlhttp:

显然,浏览器抱怨 html 格式: 未捕获的 SyntaxError:意外字符串(15:08:42:080 | 错误,javascript) 在 testJSON3.html:12

我的 xmlhttp 调用格式是否正确?

提前感谢您的帮助。

这是 JSON 文本 myTutorial.txt:

[
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name 1",
"eventDesc":"2015 class of course name 1"
},
{
"active":"1",
"courseCode":"208.01.00",
"courseName":"course name21",
"eventDesc":"2015 class of course name "
}
]

并通过下面的html来处理xmlhttp访问服务器localhost目录phpTWLLT上的文件

<!DOCTYPE html>


<html>
    <head>
        <script type='text/javascript' src='js/jquery.min.js'></script>
        <meta charset="UTF-8">
    </head>
    <body>

        <div id="id01"></div>

        <script>
            var xmlhttp = new XMLHttpRequest();
            var url = "http://localhost/phpTWLLT/myTutorial.txt";

            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var myArr = JSON.parse(xmlhttp.responseText);
                    myFunction(myArr);
                }
            };
            xmlhttp.open("GET", url, true);
            xmlhttp.send();

            function myFunction(arr) {
                var out = "";
                var i;
                for (i = 0; i < arr.length; i++) {
                    out += '<li'> + arr[i].courseCode +'</li><br>';
                }
                document.getElementById("id01").innerHTML = out;
            }
        </script>

    </body>
</html>

方法2 getJSON():

这个很有趣。如果服务器端是静态数组($DEBUG = true:),javascript 能够处理并获取浏览器显示。但是从 mysql ($DEBUG = false) 生成文本时失败。

我正在为 $DEBUG=false 工作而摸不着头脑?显然,这两种情况都生成了有效的 JSON 文本。

如果 $DEBUG 设置为真,

来自 localhost/phpTWLLT/json_encode_array.php 的输出

[{"active":"0","first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr@example.com"}, {"active":"1","first_name":"John","last_name":"Doe","age":"47","email":"john_doe@example.com"}]

在浏览器中显示的列表。 0 1

如果 $DEBUG 设置为 false,

来自 localhost/phpTWLLT/json_encode_array.php 的输出

[{"active":"1"},{"active":"1"}]

浏览器显示为空白。

html 文件:

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <!--
        <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'>    </script>
        -->
    <script type='text/javascript' src='js/jquery.min.js'></script>

    <meta charset="UTF-8">
    </head>    
    <body>

    <!-- this UL will be populated with the data from the php array -->
    <ul></ul>

    <script type='text/javascript'>
        $(document).ready(function () {
            /* call the php that has the php array which is json_encoded */
            //$.getJSON('json_encoded_array.php', function(data) { 
            $.getJSON('json_encoded_array.php', function (data) {
                /* data will hold the php array as a javascript object */

                 $.each(data, function (key, val) {

                 $('ul').append('<li id="' + key + '">' + val.active  + '</li>');
                 });

            });
        });
        </script>

    </body>
</html>

PHP 脚本:json_encoded_array.php

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */



/* set out document type to text/javascript instead of text/html */


$DEBUG = true;

if ($DEBUG) {
    header("Content-type: text/javascript");
    $arr = array(
        array(
            "active" => "0",
            "first_name" => "Darian",
            "last_name" => "Brown",
            "age" => "28",
            "email" => "darianbr@example.com"
        ),
        array(
            "active" => "1",
            "first_name" => "John",
            "last_name" => "Doe",
            "age" => "47",
            "email" => "john_doe@example.com"
        ) 
    );
} else {
    require_once('connection.php');
// $m_id= 8 has many enrolled course and 11 got exactly one course enrolled. 
    $m_id = 8;
    $p_id = 1;

    $qry1 = "SELECT distinct event.active as active, subject.code as 'courseCode', subject.name as     'courseName', event.event_desc as 'eventDesc' FROM applicant, event, subject, part where applicant.applicant_id = $m_id and applicant.event_id = event.id and event.subject_id=subject.id and part.id = subject.owner_id and part.id = $p_id order by event.active DESC, event.from_month DESC ";
    mysqli_set_charset($bd, 'utf-8');
    $result = mysqli_query($bd, $qry1);

    $arr = array();
    $i = 0;
    if (mysqli_num_rows($result) > 0) {
        while ( $rs = mysqli_fetch_assoc($result)  ) {
             $colhead = "active";
            $str = $rs['active'];

            $arr[$i] = array($colhead => $str);
            $i++;

                // just generate two record for testing
                if ($i === 2)
                break;

        }
    } 
}
echo json_encode($arr);
?>

【问题讨论】:

  • '&lt;li'&gt; 应该是 '&lt;li&gt;',请经常检查您的语法
  • @Patrick,谢谢你的建议。但是,浏览器中仍然没有显示列表。
  • 您是否遇到完全相同的错误,可能是不同的错误,或者根本没有?

标签: javascript php mysql json xmlhttprequest


【解决方案1】:

对于方法 2,您是否尝试调试 javascript 代码以检查数据变量是否包含预期数据?

您还可以检查网络选项卡以查看从您的服务器发送的响应数据是否正确。

【讨论】:

  • 如果我运行 localhost/phpTWLLT/json_encoded_array.php 生成的 json 格式文本。如果 $DEBUG=true,浏览器输出:[{"active":"0","first_name":"Darian","last_name":"Brown","age":"28","email":"darianbr@ example.com"},{"active":"1","first_name":"John","last_name":"Doe","age":"47","email":"john_doe@example.com" }] 如果$DEBUG=false,浏览器输出:[{"active":"1"},{"active":"1"}]
  • 尝试打开浏览器的调试器(F12),然后加载html文件。在调试器的网络选项卡中,您将能够看到 HTTP 请求和响应 - 检查调试版本和非调试版本之间的差异。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多