geting one by one char in jquery by Json
I have asp.net mvc 2 application. since couple of da开发者_如何学JAVAys I was trying to read the List from action of controller to Jquery by returning the Json through the action. but need lot of time and effort to resolve this.now i am able to read the json data by using :
$.getJSON('/LoadTest/GetAllQuestionsForTest', function(data) {
$.each(data, function(i,item) {
alert(item);
});
});
since, my json output is :
[{"QuestionId":2,"QuestionText":"Question 1","TopicId":1},{"QuestionId":3,"QuestionText":"Question 2","TopicId":1}]
where as I am getting here one by one char in alert box rather than string like "QuestionId". I want to read the value of "QuestionId" and "QuestionText" from this script how can i do that ? even i tried data["QuestionId"] but anable to read it
Edited
This is working for me :
$.getJSON('/LoadTest/GetAllQuestionsForTest', function(data) {
var t = $.parseJSON(data);
alert(t[0].QuestionText);
});
but showing only 0'th indexed value. I want to get count of objects in data collection. so that i can iterate it. how to do that?
You can try:
alert(data[0].QuestionId)
try to do:
$.get("/LoadTest/GetAllQuestionsForTest", function(data) {
alert(data);
var t = $.parseJSON(data);
alert(t);
})
What the output ?
btw you using this on your controller? :
return Json(object, JsonRequestBehavior.AllowGet);
I think you need to use
alert(data[i].QuestionId);
alert(data[i].QuestionText);
Function each in this case is grabbing each array. You probably want to iterate the values of the arrays with an inner each.
$.each(json, function(i,item) {
$.each(item, function(j,subitem) {
alert(subitem);
});
});
You're almost there.
It looks like
$.each(data, function(i) {
alert(data[i].QuestionId);
});
should do the trick?
i think
alert(item[i].QuestionId);
ok lets remove the each.
write
alert(data[0].QuestionId);
instead
$.each(data, function(i,item) {
alert(item);
});
精彩评论