码迷,mamicode.com
首页 > Web开发 > 详细

原生ajax

时间:2017-09-20 14:47:47      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:send   encode   function   eof   ons   log   erro   obj   tty   

function ajax() {
var ajaxData = {
type: arguments[0].type || "GET",
url: arguments[0].url || "",
async: arguments[0].async || "true",
data: arguments[0].data || null,
dataType: arguments[0].dataType || "text",
contentType: arguments[0].contentType || "application/x-www-form-urlencoded",
beforeSend: arguments[0].beforeSend || function () { },
success: arguments[0].success || function () { },
error: arguments[0].error || function () { }
}
ajaxData.beforeSend()
var xhr = createxmlHttpRequest();
xhr.responseType = ajaxData.dataType;
xhr.open(ajaxData.type, ajaxData.url, ajaxData.async);
xhr.setRequestHeader("Content-Type", ajaxData.contentType);
xhr.send(convertData(ajaxData.data));
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
ajaxData.success(xhr.response)
} else {
ajaxData.error()
}
}
}
}

function createxmlHttpRequest() {
if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
}

function convertData(data) {
if (typeof data === ‘object‘) {
var convertResult = "";
for (var c in data) {
convertResult += c + "=" + data[c] + "&";
}
convertResult = convertResult.substring(0, convertResult.length - 1)
return convertResult;
} else {
return data;
}
}

ajax({
type: "POST",
url: "https://rrc.1001.sh/index.php?r=Hotcity&m=Citys",
dataType: "json",
data: {},
beforeSend: function () {

},
success: function (msg) {
console.log(msg,‘成功的数据‘)
},
error: function () {
console.log("error")
}
})

原生ajax

标签:send   encode   function   eof   ons   log   erro   obj   tty   

原文地址:http://www.cnblogs.com/liubingboke/p/7560419.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!