Ajax辨析
Ajax辨析
最近在多个知识点涉及到了ajax请求,各个知识有所交错,知识体系上学的有些混乱,这里梳理一下
单纯的发送Ajax请求
方式1: ajax传统4步骤
- ajax的post请求
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
//执行代码
}else{
//执行代码
}
}
}
xhr.open("POST", "/ajax/ajaxRequest4", true)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send("username="+username.value+"")
- ajax的get请求
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
//执行代码
}else{
//执行代码
}
}
}
xhr.open("GET", "/ajax/ajaxRequest4?" + "username="+username+"", true)
xhr.send()
方式2:自己封装的ajax请求
- 封装的代码
function jQuery(selector){
if(typeof selector == "string"){
if(selector.charAt(0) == "#"){
//原先的dom对象还要留着,因为最终的实现还要用这些对象的方法去实现,我们无法完成
domObj = document.getElementById(selector.substring(1))
//但是由于封装了新方法,所以原先的dom对象就暂时不能用了(调用不了我们自定义的方法),要返回自定义的jQuery对象
return new jQuery()
}
}
if(typeof selector == "function"){
window.onload = selector
}
this.html = function(innerData){
domObj.innerHTML = innerData
}
this.click = function(fun){
domObj.onclick = fun
}
this.val = function(v){
if(v == undefined){
return domObj.value
}else{
domObj.value = v
}
}
this.change = function(fun){
domObj.onchange = fun
}
/**
* 有一些动态的数据不能写死
* 动态的信息有:
* 1. 请求的类型
* 2. 请求的地址
* 3. 是否异步
* 4. 提交的数据
*/
jQuery.ajax = function(jsonArgs) {
var method = jsonArgs.type.toUpperCase()
var xhr = new XMLHttpRequest()
//发送ajax请求,将文本框里的数据提交至后端
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
if (this.status == 200) {
var jsonObj = JSON.parse(this.responseText)
jsonArgs.callBack(jsonObj)
} else {
alert("异常状态码: " + this.status)
}
}
}
if (method == "POST") {
xhr.open(method, jsonArgs.url, jsonArgs.async)
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
xhr.send(jsonArgs.data)
}
if (method == "GET") {
jsonArgs.data = "?" + jsonArgs.data
xhr.open(method, jsonArgs.url + jsonArgs.data, jsonArgs.async)
xhr.send()
}
}
}
$ = jQuery
new jQuery()
- 前端调用的代码
全面测试自定义jQuery类库
方式3:用官方jQuery封装的ajax请求
//$.ajax()的参数:一个json数据
$.ajax({
async : true, // 默认为true,可以不写
contentType : "application/json", // 一个字符串,表示从浏览器发送给服务器的参数的类型,可以不写
data : {"name" : "xun", "age" : 21, "address" : "芜湖"}, // 可以是字符串,数组,json,表示请求的参数和参数值,常用json格式
dataType : "json", // 表示期望从服务器端返回的数据格式,可选的有:xml,html,text,json
error : function(){ // 表示当请求发生错误时,执行的函数
//请求出错时,执行的代码
},
success : function(data){ // 请求成功,从服务器端返回了数据,执行success函数
//data,就是responseText,是jQuery处理之后的数据
},
url : 请求的地址,
type : "get" 或者 "post" // 请求的方式,默认为get方式,不区分大小写
})
//常用:url, data, dataType, success
为了解决Ajax跨域请求问题
方式1:jsonp底层实现原理
//本质原理:通过自定义时机执行