当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Error: Undefined object! while parsing JSON using jquery

问题描述:

This should be simple but I cannot seem to get this to work correctly.

Given a JSON string that looks like this:

 {

"?xml":

{

"@version":"1.0",

"@encoding":"ISO-8859-1"

},

"results":

{

"title":"AOL Movies - Closest Theater and Showtimes",

// etc,

"theater":

{

"theaterId":"10650",

"id":"10650",

// etc

},

"movie":

[

{

"studios":"Warner Bros.",

"movieId":"61683"

}

]

}

I continually get undefined objects when trying to get to any value, for example:

data.movie, or data.results.title.

Everything "looks" ok in the output.

jQuery.ajax({

type: 'GET',

contentType: 'application/json',

url: 'handler.ashx',

data: 'zip=' + postalCodes.join(','),

success: function (payload) {

var data = that.objectifyJSON(payload); // this returns typeof = object

that.constructMoviesArray(data);

},

error: function (error) {

alert(error.responseText);

}

});

this.constructMoviesArray = function (data) {

var key, movie, theater = null;

var movies = {};

movies.items = {};

movies.length = 0;

alert(data[0].movie); // FAIL - there's clearly an array but nothing displays

I hope this is enough information; I am not experienced with JSON and jQuery so I'm struggling to figure out why I can't seem to resolve this.

网友答案:

Add the json dataType. http://api.jquery.com/jquery.ajax/

The server response is probably still a string even though you set the contentType.

jQuery.ajax({
    type: 'GET',
    contentType: 'application/json',
    url: 'handler.ashx',
    data: 'zip=' + postalCodes.join(','),
    dataType: 'json', // <--- UPDATE ME
    success: function (payload) {
        var data = that.objectifyJSON(payload); // this returns typeof = object

        that.constructMoviesArray(data);
    },
    error: function (error) {
        alert(error.responseText);
    }
});

If that doesn't help, try adding a console.log or a breakpoint to the success callback. You'll be able to take a closer look at what kind of data you are working with in payload.

success: function (payload) {
    console.log(payload);
},

Hope that helps!

网友答案:

Try Like

var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";

$.getJSON(geocodingAPI, function (json) {

    // Set the variables from the results array
    var address = json.results[0].formatted_address;
    console.log('Address : ', address);

    var latitude = json.results[0].geometry.location.lat;
    console.log('Latitude : ', latitude);

    var longitude = json.results[0].geometry.location.lng;
    console.log('Longitude : ', longitude);

    // Set the table td text
    $('#address').text(address);
    $('#latitude').text(latitude);
    $('#longitude').text(longitude);
});

Demo

分享给朋友:
您可能感兴趣的文章:
随机阅读: