简体   繁体   中英

How does one utilize JSON response data from an AJAX call?

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.

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.

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."}

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.

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM