Read JavaScript advanced programming 15-ajax,cors,jsonp,img Ping

Source: Internet
Author: User
Tags httpcontext



Usually used to jquery.ajax such methods, but often overlooked the implementation behind it, this article is to learn the Ajax Foundation and several cross-domain solutions after some of the harvest.


First, Ajax--xmlhttprequest


We are all familiar with Ajax, and its core object is XMLHttpRequest (abbreviated XHR).



1. Create the object:



This object is created in IE7 and above in support of native notation.


var xhr=new xmlhttprequest ();


2. Send the request:



Open (Type,url,isasync): The first parameter is the request type (Get,post), the second parameter is the URL to be requested, and the third parameter is the bool value that indicates whether the request is an asynchronous one. The method does not actually send a request, but only initiates a request for sending.



Send (Body): The method is used to actually send the request, and the parameter is the data content that the request is actually sent. Parameters are required and pass the parameter null, even if you do not need to send content to the server.



Note In a GET request, if the URL ends with a query string, you must encode the key and the value encodeURIComponent () first.



3. Response result : The response result of the request is automatically copied into the properties of the Xhr object.


    • Status: The state code of the response result.
    • StatusText: Response result status description.
    • ResponseText: Responds to the returned text result body;
    • Responsexml: If the content type of the response is "Text/xml", then the result is assigned in the XML DOM format in the property. If the request result is in a non-XML format, the property is null.


4. Asynchronous Request :



In most cases we need to use an asynchronous request, at which point the readystate of the request can be detected to determine whether the request has been completed. In fact, the Onstatechange event is triggered every time the ReadyState property changes. The ReadyState property has five value cases:


    • 0: Uninitialized, that is, the open () method has not been called;
    • 1: Start, the Open () method has been called, the Send () method has not been called;
    • 2: Send, has called the Send () method, has not received a response;
    • 3: Receive. has received a portion of the response result data;
    • 4: Complete. All response data has been received and can be called on the client (most commonly used).


Remarks to ensure browser compatibility, you need to specify the onReadyStateChange event handler before calling the open () method.



5. Custom HTTP request headers



setRequestHeader (Key,value): sends a custom message header. The most common scenario is to simulate a form submission in a POST request: Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");



"Remarks" The method must be called before the Open () Send ().



6. Brief example demo1.html:


var obj= document.getElementById("result");
//Create XHR object
var xhr = new XMLHttpRequest();
//State change event
xhr.onreadystatechange=function(){
obj.innerHTML+="readyState:"+xhr.readyState+"<br/>";
//Request complete
if(xhr.readyState==4){
//Response results
if ((xhr.status==200) || xhr.status == 304){
var msg="status:"+xhr.status+"<br/>";
msg+="statusText:"+xhr.statusText+"<br/>";
msg+="responseText:"+xhr.responseText;
obj.innerHTML+=msg;
} else {
Alert ("request failed:" + XHR. Status);
}
}
}
//Start request
xhr.open("get", "weather.json", true);
//Custom HTTP header
xhr.setRequestHeader("testheader","hello");
//Send request
xhr.send(null);





ii. xhr Progress Events


1.load Events



The Load event is called when the response results are received and can be used to simplify the ReadyStateChange event. However, the event is triggered as soon as the browser receives the results, so it is also necessary to determine the status of the response state.


xhr.onload=function(){
if ((xhr.status==200) || xhr.status == 304){                       
obj.innerHTML+="responseText:"+xhr.responseText;
} else {
Alert ("request failed:" + XHR. Status);
}
}


2.progress Events



The progress event is triggered periodically during the process of receiving data from the browser. The OnProgress event handler can receive the event object parameter, where Event.targe is the XHR object, and it has three important properties:


    • Lengthcomputable: Boolean value indicating whether the progress is available;
    • Loaded: The number of bytes that have been received;
    • Total: Number of bytes expected to be received based on Content-length in the response header.
xhr.onprogress=function(event){
             if(event.lengthComputable){
                  objstatus.innerHTML=event.loaded+"/"+event.total;
                  }
             }
third, cross-domain resource sharing (CORS)


One of the main constraints of XHR is the same-origin policy, that is, the same domain, the same port, the same protocol, cross-domain resource sharing can be achieved through the cross-domain resource sharing cors (Cross-origin resourse sharing). The basic idea is to have the browser communicate with the server through a custom HTTP header to determine if the response is normal. If the server allows the request, add "Access-control-allow-origin" to the response header to originate the information back and forth.



1.IE to Cors support--xdr (xdomainrequest)



The use of XDR objects in IE implements Cors, which is used similar to the XHR object and is also called the Open () and send () methods after instantiation. The difference is that the XDR's open () method has only two parameters: the request type and the URL.


xhr=new XDomainRequest();
xhr.open(method,url);
xhr.send();


2. Other browsers support cors--native XHR



Most browsers ' XHR objects natively support cors, simply passing in the URL of the response in the open () method.



3. Cross-browser support for Cors



In both cases, cross-browser cors can be achieved. The simplest way to check whether XHR supports cors is to check the Withcredentials property, and then combine to check if the Xdomainrequest object exists.


function createCORSRequest(method,url){
//Create XHR object
var xhr = new XMLHttpRequest();
//Start request
if("withCredentials" in xhr){
xhr.open(method,url,true);
}else if(typeof XDomainRequest!=‘undefined‘){
xhr=new XDomainRequest();
xhr.open(method,url);
}else{
Xhr=null;
}                 
Return XHR;
}


4. Example



Here is a simple example of http://www.jsdemo.com/demoajax/demo3.htm cross-domain request data in http://www.othersite.com/weather.ashx. This is the local construction of the two test site, the demo source see the bottom of the article.



WEATHER.ASHX first detects the source page and then decides whether to return to the Access-control-allow-origin header.


public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string referrer = context.Request.ServerVariables["HTTP_REFERER"];
if (!string .IsNullOrEmpty(referrer) &amp;&amp; referrer.IndexOf( "http://www.jsdemo.com") > -1)
{
context.Response.AddHeader( "Access-Control-Allow-Origin" , "http://www.jsdemo.com");
}
Context. Response. Write ("{" weather \ ":" sunny \ "," wind \ ":" breeze \ "}");
}


Demo3.htm cross-domain requests through cors, and the results are parsed and displayed on the page.


var xhr=createCORSRequest("get","http://www.othersite.com/weather.ashx");
         xhr.onload=function(){
              if(xhr.status==200||xhr.status==304){
                   var result=xhr.responseText;
                   var json=JSON.parse(result);
                   var obj= document.getElementById("result");
                   obj.innerHTML="天气:"+json.weather+";风力:"+json.wind;
                   }
              }
      xhr.send();



iv. Image cross-domain requests


tags are not cross-domain constrained, we can use image tags to achieve a simple, one-way cross-domain communication. Image pings are typically used to track user clicks and ad exposure times.



Features: Image cross-domain requests can only be used for one-way communication between the browser and the server, it can only send a GET request, and the service accesses the server's response content.



Let's take a look at a small example. demo4.htm triggers cross-domain requests when the client clicks a link.


<a href="javascript:void(0);" onclick="Click()">点击我</a>
    <script>
         function Click(){
              var img=new Image();
              img.onload=function(){
                   alert(‘DONE‘);
                   }
                   img.src="http://www.othersite.com/demo4.ashx?r="+Math.random();
              }
    </script>


The server makes a simple count and sends back a pixel-sized image. The client receives the result and the popup prompts "done".


public static int Count=0;

public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain" ;
        Count++;
        context.Response.ContentType = "image/gif" ;
        System.Drawing. Bitmap image = new System.Drawing. Bitmap(1, 1);
        image.Save(context.Response.OutputStream, System.Drawing.Imaging. ImageFormat .Gif);
        context.Response.Write(Count);
    }
v. JSONP cross-Domain requests


1.JSONP structure



JSONP is a common cross-domain request scheme, and the common JSONP request format is as follows:


Http://www.othersite.com/demo5.ashx?callback=showResult


The response result looks like a JSON structure wrapped in a function call:


Showresult ({"Weather": "Clear", "wind": "Breeze"})


The JSONP result consists of two parts: the callback function and the data. A callback function is typically a function that is specified at the time of the request, and is called on the page when the response completes, and the data is, of course, the result of the JSON data returned by the request.



2. Initiating the request:



The JSONP principle is implemented using dynamic <script> tags, by creating a script object and setting its SRC attribute to the URL address of a cross-domain request. When the request is complete, the JSONP response is loaded into the page and executed immediately.


<script>
function showResult(json){         
var obj= document.getElementById("result");
Obj. InnerHTML = "weather:" + JSON. Weather + "; wind:" + JSON. Wind;
}
var script=document.createElement("script");
script.src="http://www.othersite.com/demo5.ashx?callback=showResult";
document.body.insertBefore(script,document.body.firstChild);
</script> 


3. Features:


    • Jsonp can implement two-way communication between browser and server, and can access text in the response;
    • JSONP is to load code from other domains and execute it, need to pay attention to its security;
    • JSONP request result is not easy to determine success or failure.


Accessories: Demo Source



Read JavaScript advanced programming 15-ajax,cors,jsonp,img Ping


Related Article

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.