The simple operation of Jackson and Ajax

Source: Internet
Author: User
Tags error status code

Server serialization and deserialization

One, serialization

    /**     * Serialized as JSON     *    /public static string ToJson (Object obj) {        string result = null;        try {            //object mapper            objectmapper objectmapper = new Objectmapper ();            Set Date format            simpledateformat sdf = new SimpleDateFormat ("yyyy mm DD HH:mm:ss");            Objectmapper.setdateformat (SDF);            result = objectmapper.writevalueasstring (obj);        } catch (Jsonprocessingexception e) {            e.printstacktrace ();        }        return result;    }
Two, deserialization
/**     * Deserializes into objects     *     * T: Indicates that all types are different from Objcet. Generic strongly typed object is weakly type     * JSON: String that needs to be deserialized     * ValueType: deserialized type     * */     < T > T toobject (String json,class<T>  valueType) {        //object Mapper        Objectmapper mapper=new objectmapper ();        T Result=null;        try {            result=mapper.readvalue (json,valuetype);        } catch (Exception e) {            e.printstacktrace ();        }        return result;    }
third, the problem of time when serializing

Time through the Jackson serialization is a problem, it will convert the time to 1977 to the present time of the number of milliseconds, the following to solve the problem

1, Time annotation @jsonformat: Insert a time annotation before the time field that requires the specified serialized object, changing to the format you want

  

    Private String Comid;    Private String comname;    Private String Comprice;    Set Date format
/**
*locale: Country
*timezone: Time zone
*pattern: Time Format
* /@JsonFormat (locale= "zh", timezone= "gmt+8", pattern= "Yyyy-mm-dd HH:mm:ss") private String comtime; Private String yn;

2,simpledateformat: Set the time format before serializing

            Object Mapper            objectmapper objectmapper = new Objectmapper ();            Set Date format            simpledateformat sdf = new SimpleDateFormat ("yyyy mm DD HH:mm:ss");            Objectmapper.setdateformat (SDF);            Objectmapper.writevalueasstring (obj);

Jackson Toolkit:

Https://files.cnblogs.com/files/NiuBiHH/jackson.zip

four, native Ajax

Get XHR Object

     /** * Get XHR Object **/function getxhr () {//window. XMLHttpRequest objects that are almost always available in a common browser        if(window. XMLHttpRequest) {return NewXMLHttpRequest (); }Else  if(window. ActiveXObject) {//ActiveXObject ("Microsoft.XMLHTTP") is a Xhr object obtained by Microsoft Corporation under IE6 IE5            return NewActiveXObject ("Microsoft.XMLHTTP"); }        return NULL; }

Functions that are called when the state changes

      /*
*xhr.readystate equals 4 Indicates the request was successful
*xhr.status equals 200 indicates server response status is successful
*xhr.responsetext Remove the value returned by the server response
*/
  xhr.onreadystatechange=function () {            if(xhr.readystate==4) {                 if( xhr.status==                 xhr.responsetext;
           } } }

Open () If it is local, you can use Openreques () instead

/*
* method request type such as: Get post
*
* ASYCN is an asynchronous request by default is True
*/

void Open ( domstring method, domstring URL, async,);

All related events requested by send () must precede this method

Xhr.send (null

Case:


/** * Get XHR Object **/function getxhr () {//window. XMLHttpRequest objects that are almost always available in a common browser if(window. XMLHttpRequest) {return NewXMLHttpRequest (); }Else if(window. ActiveXObject) {//ActiveXObject ("Microsoft.XMLHTTP") is a Xhr object obtained by Microsoft Corporation under IE6 IE5 return NewActiveXObject ("Microsoft.XMLHTTP"); } return NULL; } function Gettime_click () {varXhr=getxhr (); //events when the state changesXhr.onreadystatechange=function () {if(xhr.readystate==4){//Request succeeded if(xhr.status== $){//Server response status succeeded//display data from the server on the pagealert (xhr.responsetext); } } } //Open RequestXhr.open ("GET","Commoditycontrol?action=time",true);//request type, path, whether it is an asynchronous request//Send RequestXhr.send (NULL);//Parameters}
Five, $.ajax (options)
$.ajax Parameter Description
Property Type Describe
wr. String The requested URL
Type String Requested method such as: Get () POST () default get ()
Data Object Parameters with past when requesting background
DataType String Sets the type of data returned by the server, such as: XML HTTP JSON SCRIPT TEXT
Timeout Numerical Set the request time to abort the request and invoke the error function if it exceeds the change time
Global Boolean value Enable or disable triggering of the complete function
ContentType String The requested content type
Success Function Called when a request succeeds, the first parameter of the function is the server's response value
Error Function The request response indicates an error status code, with three arguments called the function: Request object, status message string, exception object
Complete Function The request response indicates the success status code, called the function, and if the success or error callback function is specified, the function is called after they are called
Beforesend Function Functions called before initiating a request
Async Boolean value Specifies whether the request is asynchronous

Case:

$.ajax ({type: "get",//Request type URL: "Commoditycontrol?action=allcom", Path Beforesend:function () {//Pre-request event C.S                how ();  }, Success:function (data) {//Event $.each after successful request (data, function (index, obj) {var tr = $ ("<TR/>"); var inptd = $ ("<TD/>"); $("<inputname= ' ComCheck 'class= ' ComCheck 'type= ' checkbox '/>"). HTML (obj.comtime). AppendTo (INPTD). Data (" id ", obj.comid);                        Inptd.appendto (TR); $("<TD/>"). HTML (obj.comid). AppendTo (TR); $("<TD/>"). HTML (obj.comname). AppendTo (TR); $("<TD/>"). HTML (obj.comprice). AppendTo (TR); $("<TD/>"). HTML (obj.comtime). AppendTo (TR); var Inputtd = $ ("<TD/>"); if (Obj.yn = = ' Y ') {$ ("<inputname= ' yn 'checked= ' 'value= ' Y 'type= ' checkbox '/>"). HTML (obj.comtime). AppendTo (INPUTTD); } else {$ ("<inputname= ' yn 'type= ' checkbox '/>"). HTML (obj.comtime). AppendTo (INPUTTD);                        } inputtd.appendto (TR); var ATD = $ ("<TD/>"); $("<ahref= ' # ' class= ' aupdate '></a>"). HTML (" verbose "). AppendTo (ATD). Data (" id ", obj.comid); $("<ahref= ' # 'class= ' Adel '></a>"). html (" delete "). AppendTo (ATD). Data (" id ", obj.comid);                        Atd.appendto (TR);                        $ ("#com"). Append (tr);                    C.close ();                });                }, Complete:function () {//the event at the completion of the request, regardless of success or failure $ ("#hint"). HTML ("request complete ..."); }, Error:function (XHR, Textstatus, Errorthrown) {//Error alert (XHR + Textstatus + E                Rrorthrown); }            });

The simple operation of Jackson and Ajax

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.