Ajax based realization of JS, JSON and JSONP, implement the JQuery ajax based

Based on the JS achieve the ajax, the JSON and JSONP, based on the JQuery realization of ajax 
1. Based on the JS ajax implementation
step1: var xmlhttp = XMLHttprequest () # instantiate an object
step2: xmlhttp.open ( "") #url Address
step3: xmlhttp.send ( "name = alex ") # requested content body if GET request: Send (null)
Step4: listener: XMLHTTP (IF ==. 4: var context = {} xmlHttp.responseText)
the GET: Ajax embodied ( the JS mode):
<! DOCTYPE HTML>
<HTML lang = "EN">
<head>
<Meta charset = "UTF-. 8">
<title> the title </ title>
</ head>
<body>
<Button the onclick = "func1 ()"> ajax Submit </ button>
</body>
<script>
function func1(){
Step1 //
var XMLHTTP = createXMLHttpRequest ();
// Step4: Recommended into this position
xmlhttp.onreadystatechange = function () {// listening
{#alert (xmlhttp.status); // return a status code #}
IF (XMLHTTP. == ==. 4 && xmlhttp.status the readyState 200 is) {
{#alert (xmlHttp.readyState); // check the status of the process #}
var = Data xmlhttp.responseText;
Alert (Data);
};
}
// Step2
xmlhttp.open ( "GET", "/ ajax /", true); // open server connection
// Step3
xmlhttp.send (null); // send a request
};
{# handle browser incompatibilities #}
function createXMLHttpRequest () {
var xmlHttp;
// for most browsers, and IE7 and later
the try {
xmlHttp new new = the XMLHttpRequest ();
} the catch (E) {
// applicable to IE6
the try {
xmlHttp the ActiveXObject new new = ( "Msxm12.XMLHTTP");
} the catch (E) {
// suitable IE5.5, and earlier
the try {
xmlHttp the ActiveXObject new new = ( "Microsoft.XMLHTTP") ;
} the catch (E) {}
}
}
return xmlHttp;
}

</ Script>
</ HTML>
POST: Note request
POST request must be set ContentType request header is: file application / X-WWW-form-urlencoded.
Form enctype default value is to application / x-www-form- urlencoded, because the default value is this,
when setting <form> of enctype = time "application / x-www-form -urlencoded", equivalent to setting the Con
tent-Type request header. However, when ajax transmission request, there is no default value, which need to set their own request header:
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form>
<p>用户名:<input type="text" name="username" onblur="func1(this)">
<span id="error"></span>
</p>
<p>密码:<input type="password" name="pwd"></p>
<input type="submit" value="submit">
</form>
</body>
<script>
function func1(self){
var username=self.value;
var xmlhttp=createXMLHttpRequest();
xmlhttp.open("POST","/register/",true);
xmlhttp.setRequestHeader ( "the Content-the Type", "file application / X-WWW-form-urlencoded");
xmlhttp.send ( "username =" username +);
xmlhttp.onreadystatechange = function () {
IF (== xmlHttp.readyState == 200 is && xmlhttp.status. 4) {
var S = xmlhttp.responseText;
IF (S == ". 1") {
. document.getElementById ( "error") the innerHTML = "user name has already been registered ";
}
};
}
}
{# handle browser incompatibilities #}
function createXMLHttpRequest () {
var xmlHttp;
// for most browsers, and IE7 and later
the try {
xmlHttp new new = the XMLHttpRequest ();
} the catch (E) {
/ / for IE6
the try {
xmlHttp the ActiveXObject new new = ( "Msxm12.XMLHTTP");
} catch (e){
// suitable IE5.5, and earlier
the try {
xmlHttp the ActiveXObject new new = ( "Microsoft.XMLHTTP");
} the catch (E) {}
}
}
return xmlHttp;
}
</ Script>
</ HTML>
2.JSON and JSONP
JSON and compare XML:
readability: XML is good;
decoding difficulty: JSON itself Js objects (home game), so a lot simpler;
popularity: xml has been popular for many years, but in AJAX areas more popular json;
JS receiving the python json objects:
in the encoding process json in, there will be from python primitive type to a conversion process json type specific conversion as follows:
python json objects
dict Object
List, tuple Array
STR, Unicode String
int, Long, a float Number
To true true
False to false
None null
the JSON.parse ()
.parse () method: the parse for parsing a string from json objects
the JSON.stringify ()
.stringify () method: the stringify for a target character string parsed from
example:
$ .post ( "/ jQuery /", function (Data) {
the console.log (Data);
the console.log (typeof Data);
Data = the JSON.parse (Data); # from a string for the parse parsing json objects
the console.log (typeof Data);
the console.log (Data [ "name"]);
});
json example: // NOTE: string must be double quotes, or not json
#author: wylkjj
#date: 2019/9/6
Import JSON
F = Open ( 'text', 'R & lt')
Data reached, f.read = ()
Data = json.loads (Data)
f.close ()
Print (Data [ "name"])

Import JSON
DIC = { 'name': 'Eric'}
Data = json.loads (Data)
Print (Data [ "name"])
3. Based on the JQuery ajax implementation :( most underlying method: $ .ajax ())
$ .ajax (
URL:
type: "the POST"
)
$ .get ()
$ .post ()
$ .getJSON (): corresponds to $ .get (type: Json)
$ .getScript (): real-time loading, now with the current taken, not without loading
two kinds of ways to write:
( . 1) $ Ajax.. ({
URL: "/ /",
type: "the POST"
})
( 2) . $ Ajax (. "", {})
requesting data: data, processDate, contentType, Traditional, dataType, Sucess
data:Current ajax request to carry data, is a json of the Object object,ajax method will by default it encoded into a format ( urlencoded A = B =. 1 & 2?)
is sent to the server; Further, ajax default to get send request.
processDate: specify the current data whether data transcoding or pretreatment, the default is true, i.e. pretreatment; IF is false, then the data: {A:. 1, B: 2} calls
json object toString () method, i.e. {a: 1, b: 2 } .toString (), to give a final [Object, Object] in the form of results. The significance of this property is that when the
data is a dom structure or when the xml data, we do not want to process the data directly to the past, it can be set to true.
contentType:
Default: "file application / X-WWW-form-urlencoded", transmits information to the server when the content encoding type.
It is used to indicate the current requested data encoding format: urlencoded: A: & B. 1: 2; If you want to submit the data in other ways, such as? ContentType:
"file application / json", the server also transmits a json string:
dataType:
whendataType been declared when "json", is to tell the server "to get back to give me back json format, or I do not! ",
and automatically convert data received after the JavaScript object. available values of dataType: HTML text XML JSON Script
Success:
Success parameters: Success: function () {} function upon successful execution of
Complete:
Complete parameters: Complete: function () {} function is executed when the execution is unsuccessful
complete print of all error messages
beforeSend (XHR):
type: before sending a request to modify Function letter XMLHttpRequest object, such as adding a custom HTTP header. XMLHttpRequerst
object is the only parameter. This is an Ajax event. If it returns false to cancel the ajax request.
error:
error: function (Data) {
Alert (Data)
}
internal error, refers to the internal server error
instance:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="func1()">AJAX提交</button>
<script src="/static/jquery-3.1.1.min.js"></script>
<script>
function func1() {
Text()
}
function Text(){
//回调函数
//$.post();
//$.get("/jquery/",{name:"eric"});
//$.post("/jquery/",{name:"eric"});
$.post("/jquery_get/",{name:"eric"},function(data,stateText,obj){
//console.log(arguments);// print all parameters in the parameter object });Alert (Data);the console.log (obj);the console.log (stateText);
the console.log (Data);




}
</script>
</body>
</html>
$.ajax() 实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="func1()">AJAX提交</button>
<script src="/static/jquery-3.1.1.min.js"></script>
<script>
function func1() {
Text()
}
function Text(){
//$.post();
//$.get("/jquery/",{name:"eric"});
//$.post("/jquery/",{name:"eric"});
$.post("/jquery_get/",{name:"Eric"}, function (Data, stateText, obj) { console.log (data);
//console.log(arguments);// print all the parameters in the parameter object

the console.log (stateText);
the console.log (obj);
Alert (Data);
});
$ .ajax ({
URL: "/ jquery_get /",
type: "the POST",
// Data: {A:. 1, B: 2},
Data: {a:. 1, B: [3,4-]}, // iteration loop, deep circulation
traditional: true // default program prohibits execution of the iteration loop, deep circulation
// the processData: to false,
/ / the contextType: text,
});
}
</ Script>
</ body>
</ HTML>
4. Note: browser version compatibility issues
{# handle browser incompatibilities #}
function createXMLHttpRequest () {
var xmlHttp
// apply most browsers, and IE7 and later
the try {
xmlHttp new new = the XMLHttpRequest ();
} the catch (E) {
// applies to IE6
the try {
= the ActiveXObject new new xmlHttp ( "Msxm12.XMLHTTP");
} the catch (E) {
// suitable IE5.5, and earlier
the try {
xmlHttp the ActiveXObject new new = ( "Microsoft.XMLHTTP")
} the catch (E) {}
}
}
return xmlHttp;
}

Guess you like

Origin www.cnblogs.com/wylshkjj/p/11494718.html