This article mainly introduces the method of JSON data interaction in ASP. 4, which has certain reference value, and the interested partners can refer to it.
Front office AJAX requests often need to get JSON format data from the background, usually in the following ways:
Stitching strings
Return Content ("{\" id\ ": \" 1\ ", \" name\ ": \" A\ "}");
Double quotes are escaped in order to strictly conform to the JSON data format.
Serializes an object into a JSON-formatted string using the Javascriptserialize.serialize () method MSDN
For example, we have an anonymous object:
var tempobj=new { id=1, name= "A"}
Returns a JSON string using the Serialize () method:
String Jsondata=new JavaScriptSerializer (). Serialize (tempobj); return Content (Jsondata);
return Jsonresult type MSDN
in ASP. NET MVC, you can return a serialized JSON object directly:
Public Jsonresult Index () { var tempobj=new { id=1, name= ' A ' } return Json (Tempobj, Jsonrequestbehavior.allowget); }
The parameter ' Jsonrequestbehavior.allowget ' needs to be set to allow get requests.
When the foreground processes the returned data, for 1, 2 methods, you need to use the Parsejson method provided by jquery to convert the returned string to a JSON object:
$.ajax ({ URL: '/home/index ', success:function (data) { var result=$.parsejson (data); //... }});
For the third method, you can use it directly as a JSON object.