javascript - JSON.解析: unexpected end of data (javascript)

标签 javascript ajax json

我有几个函数可以解析外部/内部 JSON 数据并使用 localStorage 将其返回到本地网页。现在我已经获得了外部 JSON 数据以正确显示,但尚未获得本地提交的 JSON 数据并收到 JSON.parse: Unexpected end of data 错误。解析此数据的函数是 retrieveData()

以下是我正在尝试做的事情的示例。

function saveData () {  //This function take the data from the html inputs and put the values into local storage
    getRadio();
    getCheckbox();
    localStorage.setItem("Categories", $("select").value);
    localStorage.setItem("Name", $("Name").value);
    localStorage.setItem("Rating", $("rating").value);
    localStorage.setItem("Recommend", recommendValue);
    localStorage.setItem("Favorite", Favorite);
    localStorage.setItem("Date", $("date").value);
    localStorage.setItem("Notes", $("notes").value);
    alert("Resource Saved!");
}

    function getRadio () {  //This function takes the radio input; be it checked or unchecked
    var radio = document.forms[0];
    for (var i = 0; i < radio.length; i++) {
        if (radio[i].checked) {
            Favorite = radio[i].value;
        }
    }
}

function getCheckbox () { //This function takes the value from recommend; either being yes or no
    if ($("Y").checked) {
        recommendValue = $("Y").value;
    }
    else {
        recommendValue = $("N").value;
    }
}

    function retrieveData () { //this function will retrieve the data in local storage or from json.js if their is no default data
    toggle("on");
    if (localStorage.length === 0) {
        alert("No data in localStorage. Adding default data.");
        fillData();
    }
    var Makediv = document.createElement('div');
    Makediv.setAttribute("id", "games");
    var list = document.createElement('ul');
    Makediv.appendChild(list);
    document.body.appendChild(Makediv);
    //ImageGrab($("Select").value, Div);
    for (var i = 0; i < localStorage.length; i++) {
        var mli = document.createElement('li');
        list.appendChild(mli);
        var keyVal = localStorage.key(i);
        var value = localStorage.getItem(keyVal);
        //convert local storage value back into an object using JSON
        var objct = JSON.parse(value);
        var makesul = document.createElement('ul');
        mli.appendChild(makesul);
        for (var q in objct) {
            var msl = document.createElement('li');
            makesul.appendChild(msl);
            var subText = objct[q][0] + " " + objct[q][1];
            msl.innerHTML = subText;
        }
    }
}

    function fillData () { //this function reads in json.js with Ajax
    var xmlRequest;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlRequest = new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
         xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlRequest.onreadystatechange = function () {
    if (xmlRequest.readyState == 4 && xmlRequest.status == 200) {
        var text = xmlRequest.responseText;
        var json = JSON.parse(text);
    }
    xmlRequest.open("GET", "json.js?_dc" + Math.random(), false);
    xmlRequest.send();
    for (var i in json) {
        var ID = Math.floor(Math.random() * 100000001);
        localStorage.setItem(ID, JSON.stringify(json[i]));
    }
}

    function $(x) { //this function gives me the ability to call an element easily.  $("example")
    var element = document.getElementById(x);
    return element;
}

    var DisplayRatings = $('DisplayLink');  
    DisplayRatings.addEventListener("click", retrieveData); //on-click display data
    var SubmitRating = $('submit');
    SubmitRating.addEventListener("click", saveData, true); //on-click save the data

有人能指出我正确的方向吗?我之前尝试过 JSON.readyStatus === 4JSON.status === 200 但没有成功(在 if 语句中)。

我的预期输出是将其放在已经制作的 addGame.html 页面下。正如您所看到的,它假设创建一个无序列表,然后使用保存的 JSON 数据添加有序列表项。这是我接受输入的 html。

json.js 文件

{
"Game1": {
    "Categories": ["Categories:", "Xbox360"],
    "Name": ["Name:", "Call of Duty: Modern Warfare"],
    "Rating": ["Rating:", "7"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "04-01-2010"],
    "Notes": ["Notes:", "This is an FPS."]
},
"Game2": {
    "Categories": ["Categories:", "Playstation 4"],
    "Name": ["Name:", "Defiance"],
    "Rating": ["Rating:", "3"],
    "Recommend": ["Recommend:", "no"],
    "Favorite": ["Favorite:", "no"],
    "Date": ["Date:", "04-07-2011"],
    "Notes": ["Notes:", "Massive Multiplayer game."]
},
"Game3": {
    "Categories": ["Categories:", "Xbox360"],
    "Name": ["Name:", "Call of Duty: Black Ops II"],
    "Rating": ["Rating:", "8"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "06-03-2011"],
    "Notes": ["Notes:", "Great game."]
},
"Game4": {
    "Categories": ["Categories:", "PC"],
    "Name": ["Name:", "Dark Souls"],
    "Rating": ["Rating:", "9"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "08-06-2011"],
    "Notes": ["Notes:", "This game is extremely hard."]
},
"Game5": {
    "Categories": ["Categories:", "Playstation 4"],
    "Name": ["Name:", "Resident Evil 6"],
    "Rating": ["Rating:", "2"],
    "Recommend": ["Recommend:", "no"],
    "Favorite": ["Favorite:", "no"],
    "Date": ["Date:", "08-01-2012"],
    "Notes": ["Notes:", "This is not very great."]
},
"Game6": {
    "Categories": ["Categories:", "Wii"],
    "Name": ["Name:", "Wii Sports"],
    "Rating": ["Rating:", "5"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "no"],
    "Date": ["Date:", "08-02-2012"],
    "Notes": ["Notes:", "Virtual Sports."]
},
"Game7": {
    "Categories": ["Categories:", "Mac"],
    "Name": ["Name:", "Space Defenders"],
    "Rating": ["Rating:", "6"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "no"],
    "Date": ["Date:", "08-03-2012"],
    "Notes": ["Notes:", "This is a good casual game."]
},
"Game8": {
    "Categories": ["Categories:", "PC"],
    "Name": ["Name:", "Spelunky"],
    "Rating": ["Rating:", "10"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "08-03-2013"],
    "Notes": ["Notes:", "This is a randomly generated cave game."]
},
"Game9": {
    "Categories": ["Categories:", "Xbox360"],
    "Name": ["Name:", "Spelunky"],
    "Rating": ["Rating:", "10"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "08-03-2012"],
    "Notes": ["Notes:", "This is the xbox live arcade version that came out first, but had many xbox exclusives."]
},
"Game10": {
    "Categories": ["Categories:", "PC"],
    "Name": ["Name:", "Prison Architect"],
    "Rating": ["Rating:", "8"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "08-03-2012"],
    "Notes": ["Notes:", "This is a prison simulation game."]
},
"Game11": {
    "Categories": ["Categories:", "PC"],
    "Name": ["Name:", "Don't Starve"],
    "Rating": ["Rating:", "9"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "08-04-2012"],
    "Notes": ["Notes:", "This is horror survival game."]
},
"Game12": {
    "Categories": ["Categories:", "Wii"],
    "Name": ["Name:", "Super Mario"],
    "Rating": ["Rating:", "6"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "no"],
    "Date": ["Date:", "08-04-2012"],
    "Notes": ["Notes:", "Not as good as the original."]
},
"Game13": {
    "Categories": ["Categories:", "Playstation 4"],
    "Name": ["Name:", "uncharted 3"],
    "Rating": ["Rating:", "6"],
    "Recommend": ["Recommend:", "no"],
    "Favorite": ["Favorite:", "no"],
    "Date": ["Date:", "08-04-2012"],
    "Notes": ["Notes:", "Hype didn't live up to expectations."]
},
"Game14": {
    "Categories": ["Categories:", "PC"],
    "Name": ["Name:", "Dota 2"],
    "Rating": ["Rating:", "9"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "08-05-2012"],
    "Notes": ["Notes:", "Great for pro players."]
},
"Game15": {
    "Categories": ["Categories:", "Xbox360"],
    "Name": ["Name:", "EA MMA"],
    "Rating": ["Rating:", "10"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "08-06-2011"],
    "Notes": ["Notes:", "Best fighting game ever!"]
},
"Game16": {
    "Categories": ["Categories:", "PC"],
    "Name": ["Name:", "Papers, please"],
    "Rating": ["Rating:", "6"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "no"],
    "Date": ["Date:", "08-07-2012"],
    "Notes": ["Notes:", "This is a dystopian thiller."]
},
"Game17": {
    "Categories": ["Categories:", "Mac"],
    "Name": ["Name:", "Star Wars: Knights of the Old Republic"],
    "Rating": ["Rating:", "8"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "no"],
    "Date": ["Date:", "08-07-2009"],
    "Notes": ["Notes:", "This is a classic."]
},
"Game18": {
    "Categories": ["Categories:", "PC"],
    "Name": ["NRatingame:", "Counter Strike: Global Offensive"],
    "Rating": ["Rating:", "7"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "08-16-2012"],
    "Notes": ["Notes:", "One of the best FPS on the market."]
},
"Game19": {
    "Categories": ["Categories:", "Wii"],
    "Name": ["Name:", "007: Goldeneye"],
    "Rating": ["Rating:", "4"],
    "Recommend": ["Recommend:", "no"],
    "Favorite": ["Favorite:", "no"],
    "Date": ["Date:", "08-022-2012"],
    "Notes": ["Notes:", "Controls are not very accesible."]
},
"Game20": {
    "Categories": ["Categories:", "PC"],
    "Name": ["Name:", "Super Meat Boy"],
    "Rating": ["Rating:", "10"],
    "Recommend": ["Recommend:", "yes"],
    "Favorite": ["Favorite:", "yes"],
    "Date": ["Date:", "08-01-2012"],
    "Notes": ["Notes:", "One of my favorite platformers."]
}

}

addGame.html

<!DOCTYPE HTML>
<html>
<div id="headAddGame">
    <head>
        <meta charset="UTF-8">
        <meta keyword="Ratings, list, Gaming">
        <meta description="A form that will create a    specific review for each game.">
        <meta name="ROBOTS" content="INDEX, FOLLOW">
        <meta name="viewport" content="user-scalable=no, width=device-width">
         <link rel="stylesheet" type="text/css" href="styles.css">
        <script type="text/javascript" src="json.js"/></script>
        <div id="titleAddGame">
            <title>
                Add A Game
            </title>
        </div>
    </head>
</div>
<div="bodyAddGame">
    <body class="bodystyle">
        <fieldset ID="field">
            <legend class="bodyLegend">
                 Add Game
             </legend>
             <form action="#" method="post" id="form">
                 <h1 class="gameh1">
                      Select A Category:
                 </h1>
                 <select name="Category dropdown list" id="select">
                <option value="Select One">Select One!</option>
                <option value="Xbox360">Xbox360</option>
                <option value="Playstation 4">Playstation 4</option>
                <option value="PC">PC</option>
                <option value="Mac">Mac</option>
                <option value="Wii">Wii</option>
                </select>
                <h1 class="hone">
                    Game Information:
                </h1>
                <h2 class="htwo">
                    Name:
                </h2>
                <input type="text" name="Name" id="Name">
                <h2 class="htwo">
                     Rating (from one to ten, ten being the highest, one being the lowest):
                </h2>
                <input type="range" name="rating" min="1" max="10" id="rating">
                <h2 class="htwo">
                   Would you recommend?:
                 </h2>
                <label for="Y">Yes</label>
                <input type="checkbox" name="recommend" id="Y" value="Yes"><br>
                <label for="N">No</label>
                <input type="checkbox" name="recommend" id="N" value="No"><br>
                <br>
                <label for="Fav">
                    Save as a Favorite?
                </label>
                 <br>
                <input type="radio" name="Favorite" id="Fav" value="Yes">
                <br>
                <h2 class="htwo">
                    Date of review:
                </h2>
                <input type="date" name="date" id="date">
                <h2 class="htwo">
                    Notes:
                </h2>
                <textarea rows="4" cols="50" id="notes">
                </textarea>
                <input type="hidden" id="Dev" value="mobileDev">
                <br>
                <br>
                <input type="submit" value="submit" id="submit">
                <br>
            </form>
        </fieldset>
    </body>
</div>
<div id="footAddGame">
    <footer>
        <a href="#" ID="Clear">
            clear stored data
        </a>
        <a href="#" ID="DisplayLink">
            display data
        </a>
        <a href="addgame.html" id="Addgame" style="display:none;">
            Add New Item
        </a>
        <script type="text/javascript" src="main.js"/></script>
    </footer>
</div>

调用 retrieveData() 函数时的结果输出应将以下示例添加到页面。

与此类似:

  • 类别
    - 姓名
    - 评级
    - 推荐
    - 最喜欢的
    - 注释

然而,我的结果是这样的:


  • *
    *
    *
    *
    *

我只使用 JavaScript、Ajax、HTML 和 CSS。在这个问题上,它只处理 JavaScript 和 HTML(从 HTML 保存 JSON 数据,然后将其显示在 addGame.html 上)。

编辑:在从提交的 html 表单中读取值时也尝试过 JSON.stringify() 。发生同样的错误。

最佳答案

json.js 中的内容是 javascript,不是 JSON。您应该只使用“{”,而不是“var json = {”。

关于javascript - JSON.解析: unexpected end of data (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18748860/

相关文章:

javascript - 停止执行 Javascript 函数(客户端)或对其进行调整

javascript - 使用纯 JavaScript 在 html head 中插入新标签

javascript - 防止ajax的多个请求

javascript - 如何从 Json 创建动态 JavaScript 对象?

c# - json在c#问题中读取

ios - Parse.com 如何用 Json 同步来自 Web 的数据

javascript - 第 n 个 child 的 child 未显示

JavaScript 问题 : getElementsByName() doesn't work for me

javascript - Uncaught ReferenceError : response is not defined

javascript - ajax上传完成后如何刷新当前页面