Harry
Harry

Reputation: 489

How to parse the JSON object in ajax success

Iam getting a JSON response as

{
 "title": "Some title",
 "link": "http://google.com",
 "desc": "Some description",
 "items": [{"title":"some title"}]

}

I used $ajax to get the response

$.ajax({

                url : url,                          
                type: 'post',                   
                dataType:'jsonp',                   
                success : function(data) {  
                     console.log(json)
                }

                });

        };

Its gives me a 'Invalid Label' error. Since the response is coming from a different server should i use JSONP? I googled it and many suggested to ParseJSON. But how to parse it, as the console.log is not firing.

Upvotes: 3

Views: 19059

Answers (3)

user680343
user680343

Reputation: 55

First make sure that ajax request returns "data" (Looks like it returns).

{ "title": "Some title",
  "link": "http://google.com",
  "desc": "Some description",
  "items": [{"title":"some title"}]
}.

You could use this format as an associative array. Just like :

var title=data["title"]; //this will give you "some title"
var items=data["items"]; //this will give you a list of items.
var item_title=items["title"]; //process list of items similarly

etc.

Upvotes: 0

Eivind Eidheim Elseth
Eivind Eidheim Elseth

Reputation: 2354

Change the data type to json, and add &callback=? to your URL

Upvotes: 0

White Elephant
White Elephant

Reputation: 1381

The data variable being passed into the success function is the response. console.log(json) will be undefined, because the variable json doesn't exist.

$.ajax({
    url : url,                          
    type: 'post',                   
    dataType:'json',                   
    success : function(data) {  
        console.log(data);
    }
});

Upvotes: 1

Related Questions