您的位置:首页 > Web前端 > HTML5

HTML5跨域请求--POST方式

2015-12-17 09:09 691 查看
var xmlHttp;
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
if (method == "POST") {
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
}
return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}

//function callback() {
//    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
//        var b = xmlHttp.responseText;
//        alert(b);
//    }
//}

// Make the actual CORS request.
function makeCorsRequest(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) {
var text = xmlHttp.responseText;
// var title = getTitle(text);
var resultDiv = 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.');
};

var params = "Email=" + $("#email").val();
xmlHttp.send(params);
}

function urlDeal(url){
//解决缓存的转换
if (url.indexOf("?") >= 0) {
url = url + "&t=" + (new Date()).valueOf();
} else {
url = url + "?+=" + (new Date()).valueOf();
}

//解决跨域的问题
if (url.indexOf("http://") >= 0) {
url.replace("?", "&");
url = "Proxy?url=" + url;
}

return url;
}

var url = "请求的API地址";
//var params = { "Email": "123123123@qq.com" };

$("#btnPost").delegate("", "click", function () {
makeCorsRequest(url);
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: