varxmlHttp; //Create the XHR object. functioncreatecorsrequest (method, url) {varXHR =NewXMLHttpRequest (); if("Withcredentials"inchxhr) { //XHR for Chrome/firefox/opera/safari.Xhr.open (method, URL,true); } Else if(typeofXdomainrequest! = "undefined") { //xdomainrequest for IE.XHR =Newxdomainrequest (); Xhr.open (method, URL); } Else { //CORS not supported.XHR =NULL; } if(method = = "POST") {Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); } returnXHR; } //Helper method to parse the title tag from the response. functionGetTitle (text) {returnText.match (' <title> (. *)?</title> ') [1]; } //function Callback () { //if (xmlhttp.readystate = = 4 && Xmlhttp.status = =) { //var b = xmlhttp.responsetext; //alert (b); // } //} //Make the actual CORS request. functionmakecorsrequest (URL) {//All HTML5 Rocks properties support CORS.xmlHttp= Createcorsrequest (' POST ', url,true); //Xmlhttp.onreadystatechange = callback; if(!xmlHttp) {Alert (' CORS not supported '); return; } //Response handlers.Xmlhttp.onload =function () { if(Xmlhttp.readystate = = 4 && xmlhttp.status = 200) { varText =Xmlhttp.responsetext; //var title = GetTitle (text); varResultdiv = document.getElementById ("Callbacktext"); Resultdiv.innerhtml=text; //alert (' Response from CORS request to ' + text); } }; Xmlhttp.onerror=function() {alert (' Woops, there was an error making the request. '); }; varparams = "email=" + $ ("#email"). Val (); Xmlhttp.send (params); } functionurldeal (URL) {//to resolve a cached conversion if(Url.indexof ("?") >= 0) {URL= URL + "&t=" + (NewDate ()). ValueOf (); } Else{URL= URL + "? + =" + (NewDate ()). ValueOf (); } //troubleshoot cross-domain issues if(Url.indexof ("http//") >= 0) {Url.replace ("?", "&"); URL= "Proxy?url=" +URL; } returnURL; } varURL = "Requested API address"; //var params = {"Email": "[email protected]"}; $("#btnPost"). Delegate ("", "click",function() {makecorsrequest (URL); });
HTML5 cross-domain request--post mode