未捕获的SyntaxError:JSON.parse上的意外标记o

时间:2014-09-09 05:37:57

标签: javascript jquery json

我正在研究服务器api和脚本以JSON格式发送/接收数据,但是当我尝试解析收到的数据时,我得到了“未定义”,这里是示例数据:

  

[{“id”:“1”,“name”:“Item 1”,“description”:“”,“like_btn”:“烧在地狱里,   母狗 “ ”dislike_btn!“: ”原谅“},{ ”ID“: ”2“, ”名“:” 项目   2" , “说明”: “”, “like_btn”:“像   它“,”dislike_btn“:”发生更糟“},{”id“:”3“,”name“:”Item   3" , “说明”: “”, “like_btn”: “Explosed。”, “dislike_btn”:“你   非常愚蠢!“},{”id“:”4“,”name“:”Item   4“,”description“:”“,”like_btn“:”你很深   狗屎!“,”dislike_btn“:”有时会发生。“}]

这是JS代码:

function DataTransmitter()
{
    this.backendUrl = window.location.origin + '/backend/';

    /**
     * Send GET request to the selected URI
     * @param {string} uri
     * @returns {json}
     */
    this.get = function(uri)
    {
        $.ajax({
            url: this.backendUrl + uri,
            dataType: 'json',
            success: function(data)
            {
                return JSON.parse(JSON.stringify(data));
            }
        });
    }

    /**
     * Return object with all post types
     *
     * @returns {json}
     */
    this.getPostTypes = function()
    {
        return this.get('feed');
    }

    /**
     * Get posts from feed with selected type (default: best)
     *
     * @param {string} type
     * @returns {json}
     */
    this.getFeed = function(type)
    {
        var data;

        if(!type)
            type = 'best';

        if(type == 'best' || type == 'fresh')
        {
            data = this.get('feed/' + type);
        }else{
            data = this.get('feed/type/' + type)
        }

        return data;
    }
}

function AppApi()
{
    this.transmitter = new DataTransmitter();
    this.postTypes = null;

    this.getFeed = function(type)
    {
        var data = this.transmitter.getFeed(type);
        return data;
    }

    this.getPostTypes = function()
    {
        if(this.postTypes === null)
        {
            this.postTypes = this.transmitter.getPostTypes();
        }

        return this.postTypes;
    }
}

api = new AppApi();
console.info(api.getPostTypes()); //<------ Here is problem now

请帮帮我!我该如何解决这个错误?

1 个答案:

答案 0 :(得分:2)

dataType:&#39; json&#39;还做JSON.parse() 抛出错误,因为JSON尝试解析此字符串[object Object]