Ajax 對象 包含post和get兩種異步傳輸方式
更新時間:2009年07月21日 12:58:50 作者:
Ajax對象接受一個對象字面量為參數,這個對象字面量中包含method,url,success,params,fail參數
復制代碼 代碼如下:
/**
* @author Supersha
* @QQ:770104121
*/
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Ajax Document</title>
<script type="text/javascript">
//注意,編碼要同意為utf-8才能避免中文參數和返回中文的亂碼問題
function Ajax(prop){
this.action(prop); //在實例化的時候就調用action方法
}
Ajax.prototype = {
createXHR: function(){ //創(chuàng)建XMLHttpRequest對象
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xhr;
},
action: function(prop){
var xhr = this.createXHR();
if (xhr) {
var url = encodeURI(prop["url"]); //對URL進行編碼
if (prop["method"] == "GET" && url && prop["success"]) { //GET方法
xhr.onreadystatechange = function(){
(function(){ //自執(zhí)行函數用于檢查服務器的返回狀態(tài)并執(zhí)行回調函數
if (xhr.readyState == 4 && xhr.status == 200) {
prop["success"](xhr); //執(zhí)行回調函數
}
})();
};
//alert(prop["hander"] instanceof Function);
xhr.open("GET", url, true);
xhr.send(null);
}
else
if (prop["method"] == "POST" && url && prop["success"]) { //POST方法
xhr.onreadystatechange = function(){
(function(){
if (xhr.readyState == 4 && xhr.status == 200) {
prop["success"](xhr); //執(zhí)行回調函數
}
})();
};
if (prop["params"]) {
url = url.indexOf("?") > -1 ? url + "&" + prop["params"] : url +"?" + prop["params"];
}
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(null);
}
}
else
if (!xhr && prop["fail"]) {
prop["fail"]();
}
}
}
function getData(){
var ajax = new Ajax({
url: "test.php",
method: "POST",
success: onComplete,
params: "name="+escape("沙鋒") //進行編碼
});
}
function onComplete(obj){
alert(unescape(obj.responseText)); //進行轉碼
}
</script>
</head>
<body>
<input type="button" value="Get Data" onclick="getData()"/>
</body>
</html>
注釋:
Ajax對象接受一個對象字面量為參數,這個對象字面量中包含method,url,success,params,fail參數
method:"GET"或者"POST"
url:服務器端文件路徑
success:當請求沒有錯誤的時候,調用的回調函數,該回調函數帶一個XMLHttpRequest對象的參數
fail:當請求錯誤的時候調用
params:當使用POST方法發(fā)送請求是,params為參數字符串
相關文章
使用getJSON()異步請求服務器返回json格式數據的實現
下面小編就為大家?guī)硪黄褂胓etJSON()異步請求服務器返回json格式數據的實現。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06AJAX和WebService實現郵箱驗證(無刷新驗證郵件地址是否合法)
首先在項目里面添加服務引用,驗證 Email 地址是否正確(郵件地址合法、只是域名正確、郵件服務器沒有找到等等)感興趣的朋友可以參考下哈2013-05-05ThinkPHP5 通過ajax插入圖片并實時顯示(完整代碼)
這篇文章主要介紹了ThinkPHP5 通過ajax插入圖片并實時顯示功能,本文給大家分享網站代碼,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-12-12