【问题标题】:JQuery $.ajax({})- ajax parseerror and KnockoutJQuery $.ajax({})- ajax parseerror 和 Knockout
【发布时间】:2012-07-19 09:20:25
【问题描述】:

我有一个 JS(data.js) 文件,其中数据为

var Content = {
    Page1: {
        Tiles: [
        { "id": "1",
            "className": "home-test-class",
            "tileType": "widget",
            "tileColor": "red",
            "Bookmark": : {
                "Icon": "iconset", 
                "Class": "dummytext", 
                "Content": "Dummy Content",
                "URL": ""
            },
            "Tile": false,
            "SmallWidget": false,
            "Widget": false
        },
        { 
        "id": "1",
            "className": "title-class",
            "tileType": "widget",
            "tileColor": "red",
            "Bookmark": false,
            "Tile": false,
            "SmallWidget": false,
            "Widget": false
        },
        ]
    }
}

我创建了一个 INIT 方法来使用这些数据

Init = function () {
        $.ajax({
            url: 'scripts/data.js',
            dataType: "json",
            contentType: 'application/json; charset=utf-8'
        }).done(function (data) {
            $.doTimeout(1000, function () {
                console.log(data);
                LoadViewData(data);
            });

        }).fail(function (request, error) {
            //Handle Failures here.
            alert('Error' + error);
        });
        ko.applyBindings(this);
    },

它给了我一个 JsonParse 错误。

我正在使用敲除将数据绑定到 UI。当我使用 Fiddler 并检查响应时,它说“选定的响应不包含 vaid JSON 文本

请告诉我如何解决它。

【问题讨论】:

    标签: jquery json knockout.js getjson


    【解决方案1】:

    这是因为您返回的是 Javascript 文件,而不是 JSON 数据。以这种方式使用 Javascript 文件是没有意义的。

    如果您将文件更改为 包含一个 JSON 字符串(示例如下),并假设您的 $.ajax() 调用的其余部分没有问题,它将起作用。请注意,proper JSON 字符串将所有名称括在双引号中。此外,如果您通过 validator 运行 JSON,您会发现它存在一些问题(我已在示例中修复了这些问题)。

    {
        "Page1": {
            "Tiles": [
                {
                    "id": "1",
                    "className": "home-test-class",
                    "tileType": "widget",
                    "tileColor": "red",
                    "Bookmark": {
                        "Icon": "iconset",
                        "Class": "dummytext",
                        "Content": "Dummy Content",
                        "URL": ""
                    },
                    "Tile": false,
                    "SmallWidget": false,
                    "Widget": false
                },
                {
                    "id": "1",
                    "className": "title-class",
                    "tileType": "widget",
                    "tileColor": "red",
                    "Bookmark": false,
                    "Tile": false,
                    "SmallWidget": false,
                    "Widget": false
                }
            ]
        }
    }
    

    【讨论】:

    • 非常感谢您的回答。这样一目了然,非常有帮助。