【问题标题】:Javascript JSON.parse responseText "Unexpected end of input"Javascript JSON.parse responseText“输入意外结束”
【发布时间】:2012-11-25 15:20:25
【问题描述】:

运行此 JSON.parse 时,我在浏览器控制台中不断收到“未捕获的语法错误:输入意外结束”。我尝试将 $element 缩短为 $entry 但仍然没有成功:

function getFileList() {
        var elements;   
    var foo = document.getElementById("filelist");
    var xhr = new XMLHttpRequest();
    xhr.addEventListener("load", complete, true);

         // foo.innerHTML= xhr.responseText;
    xhr.onreadystatechange = function () {
        console.log(JSON.parse(xhr.responseText));

    }


    xhr.open("GET", "php/dir_list.php", true);
    xhr.send(null);

    function complete() {
        eventAssign();
        xhr.removeEventListener("load", complete, false);
    }

}



<?php
$files = array();
if ($handle = opendir('/trunk')) {
    $i = 0;
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            $element = '<li><a class="files" id="listFile'.$i.'" data-filename="'.$entry.'" href=php/download.php?filename='.$entry.'>'.$entry.'</a></li>';
            $checksum = shell_exec("sum /trunk/".$entry);
            $files[$entry] = array( $element, $checksum );
            $i++;
        }
    }
    closedir($handle);
}
$files =  json_encode($files);
echo $files;
?>

编辑:固定 getFileList() 粘贴。

为了避免混淆,问题仍然存在。这是 php dir_list.php 的 json 输出:

webserver httpfiles #php php/dir_list.php

{"lynx2.8.5rel.1-DOSc.zip":["<li><a class=\"files\" id=\"listFile0\" data-filename=\"lynx2.8.5rel.1-DOSc.zip\" href=php\/download.php?filename=lynx2.8.5rel.1-DOSc.zip>lynx2.8.5rel.1-DOSc.zip<\/a><\/li>","02625  2406\n"],"try.zip":["<li><a class=\"files\" id=\"listFile1\" data-filename=\"try.zip\" href=php\/download.php?filename=try.zip>try.zip<\/a><\/li>","18695    74\n"],"darn.tar.gz":["<li><a class=\"files\" id=\"listFile2\" data-filename=\"darn.tar.gz\" href=php\/download.php?filename=darin.tar.gz>darin.tar.gz<\/a><\/li>","56880   292\n"],"songs.txt":["<li><a class=\"files\" id=\"listFile3\" data-filename=\"songs.txt\" href=php\/download.php?filename=songs.txt>songs.txt<\/a><\/li>","43469     1\n"],"CentOS-6.3-x86_64-minimal-EFI.iso":["<li><a class=\"files\" id=\"listFile4\" data-filename=\"CentOS-6.3-x86_64-minimal-EFI.iso\" href=php\/download.php?filename=CentOS-6.3-x86_64-minimal-EFI.iso>CentOS-6.3-x86_64-minimal-EFI.iso<\/a><\/li>","04152 372736\n"]}

【问题讨论】:

  • 你的 json 是什么样子的?
  • 我不知道您是否只发布了部分代码,但您缺少 getFileList 函数中的结束 }
  • @Alex Mihai:在这种情况下,JSON 是由 PHP 生成的,因此很可能是有效的。错误是关闭}
  • 你需要检查 readystate 和 status

标签: php javascript xmlhttprequest json


【解决方案1】:

发现问题...我在一个电话中收到重复响应...我补充说: if (xhr.readyState==4 && xhr.status==200) {... 它解决了这个问题。谢谢。

【讨论】:

    猜你喜欢
    • 2021-06-23
    • 2020-11-18
    • 2018-05-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多