Javascript无法处理JSON文本文件

时间:2015-01-12 07:10:04

标签: javascript php mysql json xmlhttprequest

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

我尝试了两种方法。

方法1 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设置为true,

从localhost / phpTWLLT / json_encode_array.php输出

[{&#34;有源&#34;:&#34; 0&#34;&#34;如first_name&#34;:&#34;达里安&#34;&#34;姓氏&#34 ;: &#34;布朗&#34;&#34;年龄&#34;:&#34; 28&#34;&#34;电子邮件&#34;:&#34; darianbr@example.com"}, {&#34;有源&#34;:&#34; 1&#34;&#34;如first_name&#34;:&#34;约翰&#34;&#34;姓氏&#34;:&#34; DOE&#34;&#34;年龄&#34;:&#34; 47&#34;&#34;电子邮件&#34;:&#34; john_doe@example.com"}]

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

如果$ DEBUG设置为false,

从localhost / phpTWLLT / json_encode_array.php输出

[{&#34;有源&#34;:&#34; 1&#34;},{&#34;有源&#34;:&#34; 1&#34;}]

浏览器显示为空白。

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

1 个答案:

答案 0 :(得分:0)

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

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