Ajax And Comet:

1、Ajax The core of technology is XHR(XMLHTTPRequest object )

establish xhr object :

function createXHR(){

if(typeof XMLHttpRequest != "undefined"){

return new XMLHttpRequest();

}else if(typeof ActiveXObject !="undefined"){

if(typeof arguments.callee.activeXString !="string"){

var versions=["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],

i,len;

for(i=0,len=versions.length;i<len;i++){

try{

new ActiveXObject(versions[i]);

arguments.callee.activeXString=versions[i];

break;

}catch(ex){

// skip

}

}

}

return new ActiveXObject(arguments.callee.activeXString);

}else{

throw new Error("No XHR object available.");

}

}

2、 Use XHR object :open(),send()

1)     open() Method , receive 3 Parameters , The type of request to send , Requested URL, Boolean value indicating whether to send the request asynchronously

xhr.open("get”,”example.php”,false);

call open() Method does not actually send the request , Just start a request to send

2)     Send specific requests , Must be called as follows send() Method :

xhr.open("get”,”example.php”,false);

xhr.send(null);

send() Method to receive a parameter , Data to be sent as request body , If you do not need to send data through the request body , You have to pass in null, This parameter is required for some browsers , call send() After method , The request will be dispatched to the server

3)     When requesting synchronization ,js The code will wait for the server to respond before proceeding , After receiving the response , The data of the response will be automatically populated XHR Object properties

responseText: The text returned as the response body

responseXML: If the content type of the response is “text/xml“ or ”application/xml”, This property holds the... Containing the response data XML DOM file

status: Responsive HTTP state

statusText:HTTP Description of the State

After receiving the response , The first step is to check status attribute , To make sure that the response has returned successfully ,

if((xhr.status>=200 && xhr.status<300) || xhr.status==304){

// take http Status code is 200 As a sign of success

// Status code is 304 Indicates that the requested resource has not been modified , You can directly use the version cached in the browser

alert(xhr.responseText);

}else{

alert("Request was unsucessful:"+ xhr.status);

}

4)     Send asynchronous request , testing XHR Object's readyState attribute , To express a request / The current phase of the response process

The value of the property :

0: uninitialized , Not yet invoked open() Method

1: start-up , Has called open() Method , But not yet called send() Method

2: send out , Has called send() Method , But no response has been received

3: receive , Some response data has been received

4: complete , All response data has been received , And it has been used in customer service

Must be called on open() Method onreadystatechange Event handlers ensure cross browser compatibility

var xhr=createXHR();

xhr.onreadystatechange=function(){

if(xhr.readyState==4){

if((xhr.status>=200 && xhr.status<300) || xhr.status==304){

alert(xhr.responseText);

}else{

alert("Request was unsucessful:"+ xhr.status);

}

}

};

xhr.open("get","example.js",true);

xhr.send(null);

5)     call xhr.abort() Method ,XHR Object will stop triggering events , And no longer allow access to any response related object properties

3、HTTP Header information : Every HTTP Both the request and the response carry the corresponding header information ,XHR Object provides two kinds of headers to manipulate ( Request header and response header ) Method of information

1)     By default , send out XHR At the same time of request , The following header messages are also sent :

Accept: The type of content that browsers can handle

Accept-Charset: The character set that the browser can display

Accept-Encoding: Compression coding that browsers can handle

Accept-Language: The language of the browser's current settings

Connection: The type of connection between the browser and the server

Cookie: Any Cookie

Host: The domain of the requested page

Referer: Of the page that made the request URI

User-Agent: Browser's user agent string

2)     Use setRequestHeader() Method to set custom request header information , receive 2 Parameters : The name of the header field , The value of the header field , The method is placed in open() after ,send() Before

3)     getRequestHeader() Method to get the corresponding response header information ,getAllResponseHeaders() Method to get a long string containing all the header information

var myHeader=xhr.getResponseHeader("MyHeader");

var allHeader=xhr.getAllResponseHeader();

4、 The name and value of each parameter in the query string need to use encodeURIComponent Encoding , And then put it in URI At the end of , And all name value pairs must be created by & Separate

xhr.open("get","example.php?name1=value1&name2=value2",true);

function addURLParam(url,name,value){

url+=(url.indexOf("?")==-1 ? "?" : "&");

url+=encodeURIComponent(name)+ "=" +encodeURIComponent(value);

return url;

}

5、post:

var xhr=createXHR();

xhr.onreadystatechange=function(){

if(xhr.readyState==4){

if((xhr.status>=200 && xhr.status<300) || xhr.status==304){

alert(xhr.responseText);

}else{

alert("Request was unsucessful:"+ xhr.status);

}

}

};

xhr.open("get","example.js",true);

xhr.setRequestHander("Content-Type","application/x-www-form-urlencoded");

var form=document.getElementById("user-info");

xhr.send(serialize(form));

6、FormData

var data=new FormData();

data.append("name","zhang");

// Pass in form elements

var data=new FormData(document.forms[0]);

// Direct to send

xhr.open("get","example.js",true);

var form=document.getElementById("user-info");

xhr.send(new FormData(form));

7、 timeout :

xhr.open("get","example.js",true);

xhr.timeout=1000;   // Only applicable to ie8+

xhr.ontimeout=function(){

alert("ddddddddd");

}

xhr.send(null);

8、overrideMimeType() Methods can guarantee that the response should be done Xml Instead of plain text

overrideMimeType("text/xml")

9、 Progress events :

1)     in the light of xhr operation :

loadstart: The sub ah is triggered when it receives the first byte of the response

progress: Trigger continuously during receiving response

error: Triggered when a request error occurs

abort: Because of the call abort() Method to terminate the connection ---- Used to stop an ongoing request

load: Trigger when complete response data is received

loaded: When communication is complete or triggered error,abort,load Trigger after event

2)     Must be in open Before adding onprogress Event handler

var xhr=createXHR();

xhr.onload=function(event){

if(((xhr.status>=200 && xhr.status<300) || xhr.status==304){

alert(xhr.responseText);

}else{

alert("Request was unsucessful:"+ xhr.status);

}

};

xhr.onprogress=function(event){

var divStatus=document.getElementById("status");

if(event.lengthComputable){

divStatus.innerHTML="Received"+event.position+"of"+event.totalSize+"bytes";

}

//event.lengthComputable Indicates whether progress information can be Boolean

//event.position Indicates the number of bytes received

//event.totalSize according to Content-Length The expected number of bytes determined by the response header

};

xhr.open("get","example.js",true);

xhr.send(null);

10、 take withCredentials Property is set to true, You can specify that a request should be sent

11、 Cross browser CORS

js-Ajax And Comet More articles about

  1. [ Web Design ]Ajax、Comet And Websocket-- turn

    from http The agreement says 1996 year IETF  HTTP The working group released HTTP Agreed 1.0 edition  , The version commonly used up to now 1.1,HTTP The agreement went through 17  The development of . This kind of distribution . No state . be based on TCP Request / Response type . stay ...

  2. Ajax、Comet And Websocket

    from  http  The agreement says 1996 year IETF  HTTP The working group released HTTP Agreed 1.0 edition  , The version commonly used up to now 1.1,HTTP The agreement went through 17  The development of . This kind of distribution . No state . be based on TCP Request / Response type ...

  3. Ajax、Comet、Websocket、SSE

    from  http  The agreement says 1996 year IETF  HTTP The working group released HTTP Agreed 1.0 edition  , The version commonly used up to now 1.1,HTTP The agreement went through 17  The development of . This kind of distribution . No state . be based on TCP Request / Response type ...

  4. 21. javacript Advanced programming -Ajax And Comet

    1. Ajax And Comet 1.1 XMLHttpRequest object IE5 It's the first to introduce XHR Object browser ,IE5 China is through MSXML One of the Libraries ActiveX Object implemented . So in IE There may be MSXML2 ...

  5. js ajax post Submit ie And fox 、 The code submitted by Google is inconsistent , Leading to Chinese miscode

    Today, I met a problem. I have been looking for it for a long time and found that : Use js ajax post Submit ie And fox . The code submitted by Google is inconsistent , Leading to Chinese miscode //http://www.cnblogs.com/QGC88 $.ajax({ url ...

  6. JavaScript Learning summary 【12】、JS AJAX application

    1.AJAX brief introduction AJAX( Transliterated as : Ajax ) = Asynchronous JavaScript and XML( Asynchronous JavaScript and XML), It refers to a web development technology for creating interactive web applications ...

  7. Simple front end js+ajax Shopping cart frame ( Introduction )

    Actually , I always want to write something about myself js Let's sum up , Maybe it's the limited ability to combine it perfectly . I can only look at the code silently , incapable of action . There is really nothing to do in the company today , I suddenly thought of writing down the front-end frame of the shopping cart in the mall , Of course, I only have shopping carts here ...

  8. MVC3.0+knockout.js+Ajax Realize simple addition, deletion, modification and search

    MVC3.0+knockout.js+Ajax Realize simple addition, deletion, modification and search I haven't been in touch since I came to Beijing MVC, Many of them have been forgotten , I've been reading it lately knockout.js and webAPI, It was intended to adopt MVC+k ...

  9. js+ajax Three levels of coding linkage

    <!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title> ...

  10. No jump reception of mobile phone verification code on registration page [html+js+ajax+php]

    [ Learning notes ] source : SMS verification code is required for registration , But when you register , When you click receive captcha , There will be jumps ( fuck , This is not what I want !o(╥﹏╥)o) After searching information and reading books , Know how to use js+ajax Can achieve , I found one on the Internet ...

Random recommendation

  1. rewrite ViewPager Method , Prevent sliding the back page of an ad ,Fragment And change ! ( If the ad is set to rotate , You don't have to rewrite it ViewPager)

    public class MyViewPager extends ViewPager{ public MyViewPager(Context context) { this(context, null ...

  2. Payoneer Activation and use of European collection account - Used to receive funds from European companies and Euro Payments

    Sellers on Amazon's international platform are often asked if they need America ( Or Europe or Japan, etc ) You can only collect money from a bank account , I think this policy is Amazon's protection policy for local sellers ( The influx of a large number of Chinese low-cost Wumart sellers will cause local sellers to have no advantage ), Second, the local tax policy ...

  3. linux socket High performance server processing framework

    This blog has a lot of things http://blog.csdn.net/luozhonghua2014/article/details/37041765   Think about a high performance server processing framework 1. First, you need a memory pool ...

  4. by steghide Achieve dictionary cracking function

    steghide It's steganography Software , It can be in the picture . Hidden data in audio and other files . In view of the original steghide When decrypting data, you can't select dictionary file to decrypt , So I use python Simply implement the dictionary cracking function for it . -------- ...

  5. JAVA Design patterns —— agent ( Static proxy )

    Definition Provide a proxy for other objects , To control access to this object Use scenarios When you don't want to access an object directly , You can do it through an agent 1. I don't want to buy lunch , Colleagues help to bring  2. You don't have to go to the factory to buy a car , Go to 4s shop  3. Go to the agent's to buy train tickets , No need to go to the station ...

  6. bzoj The thousand questions project 314:bzoj3238: [Ahoi2013] differences ( The suffix array +st surface + Monotonic stack )

    https://www.lydsy.com/JudgeOnline/problem.php?id=3238 Follow bzoj3879 almost #include<cstdio> #include ...

  7. ASP.NET Core 2.0 A series of study notes -NLog Log profile

    One . newly build ASP.NET Core 2.0 MVC project , Use NuGet Search in browsing :NLog.Web.AspNetCore, As shown in the figure below : Two . Create a new one at the root of the project xml Type of nlog.config writing ...

  8. Ionic Dynamic configuration url Routing settings

    With Ionic App The increasing number of functions , Need routing url More and more settings , Don't like it in config Write a bunch of hard code in the function , One is not beautiful , Second, maintenance is also troublesome , Can we separate these data ? After searching data and various experiments , Finally find ...

  9. kdbg Installation tutorial (kali)

    One . The background that The so-called debugger , The main thing is the next breakpoint . Observation variables , It's not too complicated and it doesn't need too complicated tools . But to be specific linux In terms of platforms ,gdb It's not impossible to give more orders , But a screen is so big that it prints out a lot of things, and it's messy and it's easy to see ...

  10. prevent Xss Inject

    From the blog :https://blog.csdn.net/qq_21956483/article/details/54377947 1. What is? XSS attack XSS Also known as CSS(Cross SiteScrip ...