原生ajax请求:
???// ajax四步:创建XMLHttpRequest对象,连接服务器,发送请求,接收响应数据 ???????ajax: function (options) { ???????????options = options || {}; ???????????options.type = (options.type || "GET").toUpperCase(); ???????????options.dataType = options.dataType || ‘json‘; ???????????var xhr = new XMLHttpRequest(); ???????????var arr = []; ???????????if (options.params) { ???????????????for (var key in options.params) { ???????????????????arr.push(encodeURIComponent(key) + "=" + encodeURIComponent(options.params[key])) ???????????????} ???????????????var postData = arr.join("&") ???????????????options.url = options.url + "?" + postData ???????????} ???????????xhr.onreadystatechange = function () { ???????????????if (xhr.readyState == 4) { ???????????????????var status = xhr.status; ???????????????????if (status >= 200 && status < 300) { ???????????????????????try { ???????????????????????????options.success && options.success(JSON.parse(xhr.responseText)) ???????????????????????} catch (e) { ???????????????????????????options.success && options.success(xhr.responseText) ???????????????????????} ???????????????????} else { ???????????????????????options.fail && options.fail(status) ???????????????????} ???????????????} ???????????} ???????????if (options.type == "GET") { ???????????????xhr.open("GET", options.url, true) ???????????????xhr.send(null) ???????????} else if (options.type == "POST") { ???????????????xhr.open("POST", options.url, true) ???????????????xhr.setRequestHeader("Content-Type", "application/json") ???????????????xhr.send(JSON.stringify(options.data)) ???????????} ???????},
然后在登录时候调用,注意这里要考虑到post传参和url也传参的情况,网上大多都没有处理这种情况!!!
???login.ajax({ ???????????????????url: ‘/login‘, ???????????????????type: ‘POST‘, ???????????????????params: { ???????????????????????Phone: phone ???????????????????}, ???????????????????success: function (response) { ?????????????????????????????????}, ???????????????????fail: function (status) { ???????????????????} ???????????????})
原生ajax请求
原文地址:http://www.cnblogs.com/alhh/p/7611848.html