1. Return a json string:
Copy codeThe Code is as follows:
/** Output a string to the browser */
Protected void writeJson (String json ){
PrintWriter pw = null;
Try {
ServletResponse. setContentType ("text/plain; charset = UTF-8 ");
Pw = servletResponse. getWriter ();
Pw. write (json );
Pw. flush ();
Pw. close ();
} Catch (IOException e ){
E. printStackTrace ();
} Finally {
If (pw! = Null ){
Pw. close ();
}
}
}
2. Convert the returned json string to a json object through eval:
Copy codeThe Code is as follows:
$. Ajax ({
Data :{
"Shipmmsi": shipmmsi,
"Shipname": shipname
},
Url: "shipbk/findShipMMSIAndName. do ",
Async: true,
Type: "POST ",
Success: function (data ){
Var ships = eval ('+ data + ')');
$ ("# BindShipmmsiDiv table tbody" ..html ("");
If (ships! = Null ){
If (ships. length ){
$ ("# BindShipmmsiDiv"). show ();
Var trs = "";
For (var I = 0; I <ships. length; I ++ ){
Trs + = "<tr> <td>" + ships [I]. mmsi + "</td> <td>" + ships [I]. vesselName + "</td> </tr> ";
}
$ ("# BindShipmmsiDiv table tbody"). append (trs );
// Register a click event for tr
$ ("# BindShipmmsiDiv table tbody tr"). click (function (){
$ (This). addClass ('select _ tr'). siblings (). removeClass ('select _ tr ');
});
$ ("# BindShipmmsiDiv table tbody tr"). dblclick (function (){
FillShipMMSIAndName (this );
$ ("# BindShipmmsiDiv"). hide ();
});
}
}
}
});
3. The $ ("form"). serialize () of jquery can serialize the form data and submit it to the background. Therefore, you can use ajax to operate the form and process the returned data.
Copy codeThe Code is as follows:
$. Ajax ({
Url: 'deliverywarrant/update. do ',
Data: $ ('# myform'). serialize (),
Type: "POST ",
Success: function (data ){
Var res = eval ('+ data + ')');
If (res & res. success = true ){
Alert (res. message );
Location. href = "/godownWarrant/findToDeliveryWarrant. do? GodownWarrant. code = "+ $ (" # myform input [name = godownWarrant \. code] "). val ();
} Else {
Alert (res. message );
}
}
});
4. methods to prevent garbled characters:
Jsp page: charset: UTF-8
Servlet: UTF-8
Filter: UTF-8
Add a sentence before PrintWriter out = response. getWriter ().
Response. setCharacterEncoding ("UTF-8") can solve the garbled problem.
But remember to put it before declaring PrintWwrite.
In short, the front-end interface, java files, databases, and databases are all connected using unified encoding, so that no garbled code will occur.