Using jquery's $.ajax () makes it easy to invoke the ASP. However, JSON strings that are often returned from the background are not parsed correctly because the JSON data returned is not processed further. In fact, this only need to do an object processing, the way is not too cumbersome, is to put the string in eval () to execute once, this is also suitable for ordinary javascipt way to get JSON object, the following examples:
$.ajax ({
Type: "POST",
URL: "Json_post.aspx/getdata",
DataType: "JSON",
ContentType: "Application/json; Charset=utf-8 ",
Success:function (data) {
var dataobj = eval ("(" + DATA.D + ")"); Convert to JSON object
alert (dataobj.root.length); Number of sub-objects for output root
$.each (dataobj.root, function (I, item) {
Alert ("Name:" + Item.name + ", Value:" + item.value);
})
}
});
Background method:
public static string GetData ()
{
StringBuilder str=new StringBuilder ();
str. Append ("{root: [{name: ' 6101 ', Value: ' Beijing '}, {name: ' 6102 ', Value: ' Tianjin '}, {name: ' 6103 ', Value: ' Shanghai '},");
Str. Append ("{name: ' 6104 ', Value: ' Chongqing '}, {name: ' 6105 ', Value: ' Weinan '}, {name: ' 6106 ', Value: ' Yanan '}, {name: ' 6107 ', Value: ' Hanzhong ' }, ");
str. Append ("{name: ' 6108 ', Value: ' Yulin '}, {name: ' 6109 ', Value: ' Ankang '}, {name: ' 6110 ', Value: ' Shangluo '}]}");
return str. ToString ();
}
Note: 1. You need to import namespaces using System.Web.Services;
2. Methods must be static methods, and must have [WebMethod] declaration.
Summary:
From the server is a JSON array, such as [{id:1,name: "Kid"},{id:2,name: "Big Child"}] in the client needs to use eval ("(" ("+json Array object +") ") to process, This allows the JSON data from the server to be converted to JavaScript json.
Vs2005
such as: A single JSON object var data=eval (DATA.D);
Such as: Array JSON object var data=eval ("(" +data.d+ ")");
Note: vs2008 must be added. D To properly convert jquery JSON to JavaScript JSON object
such as: A single JSON object var data=eval (DATA.D);
Such as: Array JSON object var data=eval ("(" +data.d+ ")");
Background back JSON foreground get loop parsing