如何利用AJAX调用中的JSON响应数据?

时间:2021-11-04 20:16:54

I can't seem to execute any code from an AJAX call or utilize the JSON response. What am I missing? The call is successful, and I can see in Firebug that the script executes fine on the server side, but I can't seem to do anything with the data that comes back.

我似乎无法从AJAX调用执行任何代码或使用JSON响应。我错过了什么?调用成功,我可以在Firebug中看到脚本在服务器端执行正常,但我似乎无法对返回的数据做任何事情。

review.single = {
    id: null,
    ip: null,
    el: null,
    addFlag: function(){
        if(this.id && foo.user_id){
            $.ajax({
                type: 'post',
                url: '/reviews/add_flag/',
                data: ,
                dataType: 'json',
                success: function(data){
                    if(data.success){
                        this.el.text('Flagged');
                        this.el.css({
                            'text-indent': none,
                            backgroundColor: '#c00',
                            color: '#fff'
                        })
                    } else {
                        $('#growl').text(data.message);
                        $('#growl').fadeIn(500).delay(5000).fadeOut(200);
                    }                   
                }
            })
        }
    }   
}

I get this back on one of the calls response types:

我在其中一个调用响应类型上得到了回复:

{success: false, message: "You have already flagged this item."}

Ideally, I'd like to be able to take the message and throw it into the growl and show it, and use the success property as a check.

理想情况下,我希望能够接收消息并将其抛入咆哮并显示它,并使用success属性作为检查。

UPDATE:

更新:

I added an error block; looks like this:

我添加了一个错误块;看起来像这样:

error: function (request, status, error) { 
    alert(request.responseText); 
}

As a result, I get an alert that says:

结果,我收到一条警告:

{success: false, message: "You have already flagged this item."}

1 个解决方案

#1


1  

Figured it out.

弄清楚了。

My JSON was apparently not formatted correctly, and the properties needed to be wrapped in ". This threw an error back to jQuery. Thanks for the help, guys.

我的JSON显然没有正确格式化,并且属性需要包装在“。这会给jQuery带来错误。感谢您的帮助,伙计们。

Example:

例:

{"success": false, "message": "You have already flagged this item."}

#1


1  

Figured it out.

弄清楚了。

My JSON was apparently not formatted correctly, and the properties needed to be wrapped in ". This threw an error back to jQuery. Thanks for the help, guys.

我的JSON显然没有正确格式化,并且属性需要包装在“。这会给jQuery带来错误。感谢您的帮助,伙计们。

Example:

例:

{"success": false, "message": "You have already flagged this item."}