jquery has a lot of encapsulation of Ajax, which makes Ajax very convenient to use and saves a lot of code. 1. Front Code
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <!
DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
2. Code explanation
1 The first step in using jquery is to introduce the jquery library, where I put the jquery library under the JS folder under the project root directory.
<!--introduction of jquery Library--
<script type= "Text/javascript" src= "Js/jquery.js" ></script>
2 JSON string processing method
JSON string processing method
function Jsonstr () {
$.ajax ({
URL: "Jsonstr",
dataType: "JSON",
success:function (data) {
$ ("#username"). Val (data.name);
$ ("#id"). Val (data.id);
}
});
3 jquery, we do not need to go to new XMLHttpRequest (), and do not have to focus on compatibility issues between browsers, here jquery has been handled for us, the byte using $.ajax can be, in the callback function, old-fashioned writing, you need to write:
Xhr.onreadystatechange = function (data) {
if (xhr.readystate = = 4 && Xhr.status = =) {
...
}
But in the notation of JQuery, a success:function (data) {...} Yes, it's a lot easier. Attach an old-fashioned Ajax request code
function Jsonstr () {
/** old notation
var xhr = new XMLHttpRequest ();
Xhr.open ("Get", "jsonstr");
Xhr.onreadystatechange = function (data) {
if (xhr.readystate = = 4 && Xhr.status = =) {
//Convert JSON string to JS On object
var obj = eval ("(" + Data.target.responseText + ")");
document.getElementById ("username"). Value = Obj.name;
document.getElementById ("id"). value = obj.id;
}
};
Xhr.send (null);
*
/$.ajax ({
URL: "Jsonstr",
dataType: "JSON",
success:function (data) {
$ ("#username"). Val (data.name);
$ ("#id"). Val (data.id);
}
});
Turn: The Ajax of the first knowledge of jquery