Recently, when using JQuery's ajax method, the returned data is required to be json data. The following problems are encountered during the processing process: when using different methods to generate json data, at $. the following describes how to process the ajax method. Because I am using asp.net, all pages are processed. net! Other methods should be the same.
First, provide The json Data to be transmitted: [{"demoData": "This Is The JSON Data"}]
1. Use a normal aspx page for processing
I think this method is the easiest to handle. Let's look at the following code.
$. Ajax ({
Type: "post ",
Url: "Default. aspx ",
DataType: "json ",
Success: function (data ){
$ ("Input # showTime"). val (data [0]. demoData );
},
Error: function (XMLHttpRequest, textStatus, errorThrown ){
Alert (errorThrown );
}
});
Here is the code for passing data in the background
Response. Clear ();
Response. Write ("[{\" demoData \ ": \" This Is The JSON Data \ "}]");
Response. Flush ();
Response. End ();
This processing method directly parses the transmitted data into json data. That is to say, the front-end js code here may directly parse the data into json object data instead of string data, for example, data [0]. demoData: The json object data is directly used here.
2. Use webservice (asmx) for processing
This method does not treat the transmitted data as json object data, but as a string for processing. The following code:
$. Ajax ({
Type: "post ",
Url: "JqueryCSMethodForm. asmx/GetDemoData ",
DataType: "json",/* This sentence can be used but not affected */
ContentType: "application/json; charset = UTF-8 ",
Success: function (data ){
$ ("Input # showTime"). val (eval ('+ data. d +') [0]. demoData );
// There are two data conversion methods. The two processing methods have the same effect. // $ ("input # showTime "). val (eval (data. d) [0]. demoData );
},
Error: function (XMLHttpRequest, textStatus, errorThrown ){
Alert (errorThrown );
}
});
The following is the asmx method code.
[WebMethod] www.2cto.com
Public static string GetDemoData (){
Return "[{\" demoData \ ": \" This Is The JSON Data \ "}]";
}
The processing method here treats the transmitted json data as a string, and the data must be processed eval so that it can become a real json object data,
3. Use the ashx file for processing.
This method is the same as the normal aspx page processing, so I will not explain it here.
Author: xiahuawuyu