How to use Ajax to invoke the C # background method.
directory of this document
- How to use Ajax to invoke the C # background method.
- 1. Background (. cs) test method
- 2. The foreground call (JavaScript) code:
In the usual webform, we typically use "generic handlers" to respond to Ajax requests. Today we try to use Ajax to invoke the. cs file method.
1. Background (. cs) test method
[WebMethod] public static string Displayimagesinfo () {list<imagequeueinfo> Imageli St = new List<imagequeueinfo> {new imagequeueinfo{imagename= "test1", imageurl= "Http://imag Es.aiyingshi.com/productpicpath/xl/170498.jpg "}, New Imagequeueinfo{imagename=" Test2 ", imageurl=" Http://imag Es.aiyingshi.com/productpicpath/xl/170498.jpg "}, New Imagequeueinfo{imagename=" Test3 ", imageurl=" Http://imag Es.aiyingshi.com/productpicpath/xl/170498.jpg "}, New Imagequeueinfo{imagename=" Test4 ", imageurl=" Http://imag Es.aiyingshi.com/productpicpath/xl/170498.jpg "}, New Imagequeueinfo{imagename=" Test5 ", imageurl=" Http://imag Es.aiyingshi.com/productpicpath/xl/170498.jpg "}, New Imagequeueinfo{imagename=" Test6 ", imageurl=" Http://imag Es.aiyingshi.com/productpicpath/xl/170498.jpg "}, New Imagequeueinfo{imagename=" Test7 ", imageurl=" Http://imag Es.aiyingshi.com/productPicpath/xl/170498.jpg "}, New Imagequeueinfo{imagename=" Test8 ", imageurl=" http://images.aiyingshi.com/Product Picpath/xl/170498.jpg "},}; JavaScriptSerializer Jsonserializer = new JavaScriptSerializer (); String imageinfostr = Jsonserializer.serialize (ImageList); return imageinfostr; }
JavaScript calls the background method with a few points to note:
- Need to introduce a namespace:
Using System.Web.Services;
This allows you to use the [WebMethod] attribute.
Using System.Web.Script.Serialization;
Introduced the Microsoft serialization namespace.
- The called method must be declared as a static method of public.
2. The foreground call (JavaScript) code:
<script type= "Text/javascript" src= "content/js/jquery-1.8.2.js" ></script> <%--<script type= "Text/javascript" src= "content/js/jquery-1.8.2-vsdoc.js" ></script>--%> <script type= "text/ JavaScript > $ (document). Ready (function () {$.ajax ({type: "POST", cont Enttype: "Application/json", url: ' Default.aspx/displayimagesinfo ', DataType: ' JSON ', Success:function (data) {var dataobj = eval ("(" + DATA.D + ")"); $.each (dataobj, function (I, item) {$ ("#imageslist"). Append ("<li></li> "); })}, Error:function () {alert ("error!"); } }); }); </script>
- Type: You need to use the Post method.
- URL: Address/method signature
Next is the focus of today: a bit of JSON parsing problem, forget about it.
The Microsoft Framework returns data for {"D": "Data returned in the background"} by default. How do we resolve it next?
How do we get the value of ImageName and ImageUrl?
We will return the DATA.D. Reassemble into a JSON array
var dataobj = eval ("(" + DATA.D + ")");
Reference
JavaScript calls C # Backend methods and JSON parsing