开发者

Can't reference keys in returning JSON

开发者 https://www.devze.com 2023-01-26 22:35 出处:网络
I\'m returning some JSON from the web server, but I am unable to reference any of the keys. {\"voteid\":110.0,\"message\":\"Your request was processed.\",\"success\":true}

I'm returning some JSON from the web server, but I am unable to reference any of the keys.

{"voteid":110.0,"message":"Your request was processed.","success":true}

Alerting response.message/voteid alerts undefined

alert(response.voteid);

Alerting the full string works fine: alert(response); but that's no good since I want to reference the keys individually. My end goal is to get the voteid key from the JSON and append it to a anchor, which also does not work--with a full string or just a key:

success: function(response) { $(".fav").data("voteid", response.voteid) }
<a class="fav" data-voteid="">

On a side note, I don't know why there's a 0 at the end of the voteid. I'm returning the number as a string!

EDIT: Fixed by setting the dataType to JSON, however, the data will not append to the anchor's data-v开发者_JAVA百科oteid attribute.

EDIT Got it to append the id by using .attr instead of .data -- many thanks everyone!


You've excluded some key parts of your code, but I'm guessing you haven't set dataType:'json' for your request.

Or you could manually call $.parseJSON:

success: function(response) { 
    var parsed = $.parseJSON( response );
    $("fav").data("voteid", parsed.voteid);
}

Remember, JSON is text.


You're probably getting back your JSON as a string when you want it back as an object. Try the following:

var responseObject = eval(response);

alert(responseObject.voteId)

and then google for why eval is not a good idea and how to work around that.


Are you specifying the datatype as json in your ajax call? Its probably returning the JSON as a string which won't allow you to access the keys. If you specify JSON jquery will convert the string into an object

0

精彩评论

暂无评论...
验证码 换一张
取 消