JS Operation AJAX

Source: Internet
Author: User

<title>JS Operation AJAX</title> JS Operation Ajaxtable of Contents
    • Api
    • Synchronous and asynchronous
    • Ajax/text
      • Server
      • Get
      • Post
    • Ajax/json
      • Server
      • Get
      • Post
    • Ajax/xml
      • Server
      • Get
      • Post
    • Cross-domain
    • Related reading
Api as a unsigned byte array
onreadystatechange
readystate
responsebody
responsestream
responsetext
responsexml
status
statustext
Abort Cancel the current request
getAllResponseHeaders Get all HTTP headers for the response
getResponseHeader Gets the specified HTTP header from the response information
Open Creates a new HTTP request and specifies the method, URL, and authentication information (user name/password) for this request
Send Send a request to the HTTP server and receive a response
setRequestHeader Specify an HTTP header for the request individually

ReadyState:
0:unset
1:opened
2:headers_received
3:loading
4:done

Synchronous and asynchronous
<script  type    = > var xhr = new XMLHttpRequest ();   Xhr.open (' Get ', ' test.php?id=2 ', false);   Xhr.send (); alert (xhr.responsetext); </script ; 
if (! Empty ($_get[' id '])) {    echo' id = '$_get[' id 'else {    echo ' fail ';}
The third argument to open that indicates whether to use Async, false to use synchronous

If the above JS code, using True, that is, asynchronous, then will be alert '

Async indicates that the function has not been completed and can continue execution alert(xhr.responseText) , so responseText there is no time to return

Synchronous and asynchronous like a phone call to do a little thing, if it is in a synchronous way, then you will always call until the other side to answer, reply and so on; If it's asynchronous, then you just need to send a message waiting for the other person to respond.

So the above code we do in a synchronous manner, the alert of the line of code 不会那么快返回 , but wait for the send completely finished, so the program can be normal execution

How Async is implemented

Async does not block JS only one thread, executed in a queue (implementing ' multiple tasks ' is using async to ' queue ')
Ajax/textserver

test1.php

<?phpHeader' Content-type:text/plain; Charset:utf-8 ');if(isset($_get[' num '])) {Echo ' Get:ok num = ',$_get[' num '];}if(isset($_post[' num '])) {Echo ' Post:ok num = ',$_post[' num '];}
Get

Test1.html

var Request=New XMLHttpRequest();var URL=' test1.php?num= '+ 123;request.open (' GET 'Urltrue); Request.send (); request.onreadystatechange =function() {if(Request.readystate = = 4) {if(Request.status = = 200) {var Data= Request.responsetext;        alert (data); }Else{Alert (' fail: '+ Request.status +", "+ Request.statustext); }    }}
Post

Test1.html

var Request=New XMLHttpRequest(); Request.open (' POST ',' test1.php ',true); Request.setrequestheader (' Content-type ',' application/x-www-form-urlencoded '); Request.send (' num=123 '); Request.onreadystatechange =function() {if(Request.readystate = = 4) {if(Request.status = = 200)        {alert (request.responsetext); }Else{Alert (' fail: '+ Request.status +', '+ Request.statustext); }    }}
Ajax/jsonserver

test2.php

<?php// header (' Content-type:text/javascript; Charset:utf-8 '); # This is a support// header (' Content-type:text/plain; Charset:utf-8 '); # This is a supportHeader' Content-type:text/json; Charset:utf-8 ');if(isset($_get[' num '])) {Echo ' {' res ': ' Get ok! This is JSON data! num = '.$_get[' num '].'. '} ';}if(isset($_post[' num '])) {Echo ' {' res ': ' Post ok! This is JSON data! num = '.$_post[' num '].'. '} ';}
Get

Test2.html

var Request=New XMLHttpRequest();var URL=' test2.php?num= '+ 123;request.open (' GET 'Urltrue); Request.send (); request.onreadystatechange =function() {if(Request.readystate = = 4) {if(Request.status = = 200) {var Data= Json.parse (Request.response);        alert (data.res); }Else{Alert (' fail: '+ Request.status +", "+ Request.statustext); }    }}
Post

Test2.html

var Request=New XMLHttpRequest();var URL=' test2.php '; Request.open (' POST 'Urltrue); Request.setrequestheader (' Content-type ',' application/x-www-form-urlencoded '); Request.send (' num=123 '); Request.onreadystatechange =function() {if(Request.readystate = = 4) {if(Request.status = = 200) {var Data= Json.parse (Request.response);        alert (data.res); }Else{Alert (' fail: '+ Request.status +', '+ Request.statustext); }    }}
Ajax/xmlserver
<?phpHeader' content-type:text/xml; Charset:utf-8 ');if(isset($_get[' num '])) {Echo ' <mes><res>this is get data and num = '.$_get[' num '].' </res></mes> ';}if(isset($_post[' num '])) {Echo ' <res>this is POST data and num = '.$_post[' num '].' </res> ';}
Get

Test3.js

var Request=New XMLHttpRequest();var URL=' test3.php?num= '+ 123;request.open ("GET"Urltrue); Request.send (); request.onreadystatechange =function() {if(Request.readystate = = 4) {if(Request.status = = 200) {var xmldom= Request.responsexml;var Data= Xmldom.getelementsbytagname (' Res ');        alert (Data[0].childnodes[0].nodevalue); }    }}
Post

Test3.js

var Request=New XMLHttpRequest();var URL=' test3.php '; Request.open ("POST"Urltrue); Request.setrequestheader (' Content-type ',' application/x-www-form-urlencoded '); Request.send (' num=123 '); Request.onreadystatechange =function() {if(Request.readystate = = 4) {if(Request.status = = 200) {var xmldom= Request.responsexml;var Data= Xmldom.getelementsbytagname (' Res ');        alert (Data[0].childnodes[0].nodevalue); }    }}
Cross-domain
    1. Agent (not understand)
    2. Jsonp
    3. XHR2
      XHR2 Allow cross-domain
      Header ("Content-type:application/json;charset=utf-8"); header (' access-control-allow-origin: * ' ) );               * Alternative headers (' Access-control-allow-methods:post,get ') may be used ;

Jsonp

<?php Echo ' func ({"url": "Www.example1.com"}) ';
function func (data) {    alert (data.url);} var Newscript = document.createelement (' script '); Newscript.setattribute (' src ') test.php ');d ocument.getelementsbytagname (' head ') [0].appendchild (Newscript);

The principle of JSONP is to use script to cross the domain and then wrap the requested content into a function, such as Func ({...}), the parameter is the data you requested, so that is called our local func function, then we can define a Func functionfunction func(data) { alert(data...); }

Note: script will be executed automatically if it is placed inside the head (corresponding to the second code above)

jquery Jsonp

function func (data) {    alert (data.url);} $ (' input '). Click (function () {    $.ajax ({        url' http://127.0.0.1/test.php ') ,        ' Jsonp ',        ' func '    });

Xhr2

Header ("Content-type:application/json;charset=utf-8"); Header (' Access-control-allow-origin: * ');              * Alternative headers (' Access-control-allow-methods:post,get ') may be used;
Related reading
    • Other brushless technology
    • IO model, understanding synchronous and asynchronous
    • JQuery Operation AJAX
    • AJAX Introduction
    • JS Operation AJAX

JS Operation 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.