Jquery ajax ashx json usage summary

  • 2020-03-30 01:40:05
  • OfStack

The simplified version of the ajax invocation method provided by jquery is usually as follows:


    function post() { 
    $("#divWait").show(); 
    $("#btnPost").attr("disabled", "disabled"); 
    $.post("../PostIt.ashx", 
                    { 
                        msgContent: $("#msgContent").val() 
                    }, 
                    function (data) { 
                        if (data.indexOf('OK') > -1) { 
                            alert(data); 
                        } 
                        else {
                            } 
                        $("#divWait").hide(); 
                        $("#btnPost").attr("disabled", ""); 
                    }); 
}

At development time, when you want to accept a return value in json format, the above method looks like it can't be a line, and the above method looks like it accepts a line of text in text. Therefore, the underlying Ajax implementation method of jQuery is adopted.

The method parameters are also many, specific can see the help document. My regular usage


    function doPostAjax(){ 
            $("#divWait").show(); 
            $("#btnPost").attr("disabled", "disabled"); 
            $.ajax({ 
                url: '../PostIt.ashx', 
                type: 'POST', 
                dataType: 'json', 
                data: { msgContent: $("#msgContent").val() }, 
                timeout: 60000, 
                error: function (XMLHttpRequest, textStatus, errorThrown) {//Method executed when an error is requested
                    alert("error!" + errorThrown); 
                    $("#divWait").hide(); 
                    $("#btnPost").attr("disabled", ""); 
                }, 
                success: function (data, txtSataus) {//Method to execute when the request succeeds
                    showContent(data.content, data.createdate); 
                    $("#divWait").hide(); 
                    $("#btnPost").attr("disabled", ""); 
                }
                }); 
        }

In the ashx snippet, set the format of the return.

The context. The Response. ContentType = "application/json";

If it's returned HTML or text, you can write it like this

The context. The Response. ContentType = "text/plain";

If the return value set in the ajax method is json, the ashx code must return data in json format.
Converts an object into a json format, commonly used method is to use open source third-party libraries of json.net, Newtonsoft. Json. DLL.

JsonConvert SerializeObject method can be changed. Once the json format is returned, jquery can get the value as xxx. XXX.

JsonConvert returns an absolute value similar to 1198908717056 when working with the datetime format, so make a conversion when working with datetime. The specific statement is as follows:

IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();                    
// custom date format is used here, if not, the default is ISO8601 format                      
TimeConverter. DateTimeFormat = "yyyy MM '-', '-' dd 'HH' : 'the MM' : 'ss";
String output = JsonConvert. SerializeObject (m, Newtonsoft. Json. Formatting. Indented, timeConverter);

By the way, javascript has a natural ability to handle json-formatted data and is very compatible with json-formatted data.

For example:


    function pppp() { 
           var person = { "name": "jack", "age": 24,"sex": true }; 
           alert(person.name); 
           alert(person.age); 
           alert(person.sex); 
           }

Such code can be written directly, and there are code hints in the vs2010 code editor. Very powerful.

The complete code of ashx is as follows:


using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Threading; 
using Newtonsoft.Json; 
using Newtonsoft.Json.Converters;
    namespace nnn
{ 
    /// <summary> 
    /// summary of PostIt
    /// </summary> 
    public class PostIt : IHttpHandler 
    {
            public void ProcessRequest(HttpContext context) 
        { 
            context.Response.ContentType = "application/json"; 
            try 
            { 
                string msgContent = context.Request["msgContent"] ?? ""; 
                ModelContent m = new ModelContent() 
                { 
                    author = "", 
                    categoryid = -1, 
                    title = "", 
                    content = msgContent, 
                    datetime = DateTime.Now, 
                    key = "", 
                    createdate = DateTime.Now, 
                    lastmodifydate = DateTime.Now, 
                    ip = context.Request.UserHostAddress
                    };
                    //BLLContent bll = new BLLContent(); 
                //bll.Add(m);
                    IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();          
                //Custom date format is used here, if not, the default is ISO8601 & NBSP;                  
                timeConverter.DateTimeFormat = "yyyy'-'MM'-'dd' 'HH':'mm':'ss"; 
                string output = JsonConvert.SerializeObject(m, Newtonsoft.Json.Formatting.Indented, timeConverter); 
                context.Response.Write(output); 
            } 
            catch (Exception ex) 
            { 
                context.Response.Write(ex.Message); 
            }
            }
            public bool IsReusable 
        { 
            get 
            { 
                return false; 
            } 
        } 
    } 
}


Related articles: