標籤:win error: 複雜 val orm ons request params element
js原生中,ajax互動繁瑣複雜,很容易就寫錯了.因此封裝了一個跟jq差不多的函數,從此再也不用擔心ajax寫錯了,簡直神清氣爽.
//封裝的方法
function AJAX(obj){
//做網路請求的時候,參數以"對象"的形式傳遞進來
//規定: obj 裡麵包含屬性:
//1.url
//2.type -- get 還是 post
//3.data -- 前端給後端傳遞的參數(前端傳遞的時候,以"對象"的形式)
//4.回呼函數 -- success
//5.回呼函數 -- error
var ajaxObj = null;
if (window.XMLHttpRequest) {
ajaxObj = new XMLHttpRequest();
}else{
ajaxObj = new ActiveObject("Microsoft.XMLHTTP");
}
//檢測狀態的變化
ajaxObj.onreadystatechange = function(){
if (ajaxObj.readyState == 4) {
if (ajaxObj.status >= 200 && ajaxObj.status < 300 || ajaxObj.status == 304) {
if (obj.success) {
obj.success(JSON.parse(ajaxObj.responseText));
}else{
alert("您忘記了 success 函數");
}
}else{
if (obj.error) {
obj.error(ajaxObj.status);
}else{
alert("您忘記了 error 函數");
}
}
}
}
// type 轉化為小寫
var type = obj.type || "get";
type = type.toLowerCase();
//判斷是否傳遞了參數
var params = "";
if (obj.data) {
for(var key in obj.data){
params += (key + "=" + obj.data[key] + "&");
}
params = params.slice(0,params.length-1);
}
if (type == "get") {
ajaxObj.open(type,obj.url+"?"+params,true);
ajaxObj.send(null);
}else{
ajaxObj.open(type,obj.url,true);
ajaxObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajaxObj.send(params);
}
}
//html測試代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="button" value="網路測試" id="btn">
</body>
</html>
<script src="ajax.js"></script>
<script>
var btn=document.getElementById("btn");
btn.onclick=function() {
AJAX({url:"http://127.0.0.1/160811/PHP/ajax/2.php",
type:"get",
data:{
userName:"admin",
userPwd:"23123"
},
success:function(data){
console.log(data);
},
error:function(error){
console.log(data);
}
})
}
</script>
AJAX-js原生封裝