How to work withJSON data after calling an AJAX function in jQuery
With this code:
$("#mybutton").click(function(){
$.ajax({
url: '/Member/GetPinPoints/@Model.Id',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function() {
alert("error");
}
});
return false;
});
I am receiving a JSON object that looks like this:
[{"Position":1,"Top":182,"Left":20,"Height":73,"Width":90},{"Position":2,"Top":69,"Left":103,"Height":98,"Width":1}]
开发者_开发技巧How can I iterate through this data, lets say if i wanted to alert each separate value?
Plain old JavaScript:
for(var i = 0; i < data.length; i++){
for(var key in data[i]){
alert(key + " : " + data[i][key]);
}
}
And jQuery:
$.each(data, function(index, element){
$.each(element, function(key, value){
alert(key + " : " + value);
});
});
You need to iterate in a nested loop since you need to go over all elements in the array and for each array element, go over all properties.
The previous examples will work, but they are naive. No good at coding's example will just loop through an array, which isn't very robust.
Let's pretend that you return key/value pairs in your code behind method and you want to be able to pick apart this data to use however you want. You start with this.
[WebMethod]
public static Dictionary<string, string> EditPromo(int promoId)
{
using (var db = new DataContext())
{
var q = db.Promos.Where(x => x.promoID == promoId).Select(x => x).Single();
return new Dictionary<string, string>()
{
{"code", q.code},
{"label", q.label},
{"expiredate", string.Format("{0:M/d/yyyy}", q.expireDate)}
};
}
}
Now we can access it via jQuery Ajax like so:
$.ajax({
url: "/Manager/mPromo/Promo.aspx/EditPromo",
context: $("#editPromo"),
data: "{promoId:'" + promoid + "'}",
success: function (msg)
{
var resp = msg.d;
$("h1:first", this).text("Edit " + resp.code);
$("input#txtDate", this).val(resp.expiredate);
}
});
Notice how I created a variable to hold msg.d, called resp. I can then use resp.ReturnedDictionaryKey. Above I used used code and expiredate. I can use them however I please.
Try this.
$("#mybutton").click(function(){
$.ajax({
url: '/Member/GetPinPoints/@Model.Id',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
//asp.net 3.5 plus wraps the return into a .d property
var msg = data.hasOwnProperty("d") ? data.d : data;
for(var i=0; i < msg.length; i++){
alert(msg[i].Position);
}
},
error: function() {
alert("error");
}
});
return false;
});
精彩评论