Web
前端-Ajax
基础技术(上)
ajax
是浏览器提供一套的api
,用于向服务器发出请求,接受服务端返回的响应,通过javascript
调用,实现通过代码控制请求与响应,实现网络编程。
ajax
发送请求:
<!DOCTYPE html>
<html lang="en">
<head><meat charset="UTF-8"><title>Ajax</title>
</head>
<body><script>// ajax是一套api核心提供的类型:var xhr = new XMLHttpRequest();xhr.open();xhr.send();xhr.onreadystatechange = function(){if(this.readyState != 4) return// 获取响应的内容console.log(this.responseText);}</script>
</body>
</html>
复制代码
<script>
var xhr = new XMLHttpRequest()
console.log(xhr.readyState);xhr.open('GET', 'xxx.php')
console.log(xhr.readyState); // 1 初始化 请求代理对象xhr.send()
console.log(xhr.readyState); // 1xhr.addEventListener('readystatechange', function(){// if(this.readyState != 4) return// console.log(this.readyState);
})
复制代码
// ajax创建一个XMLHttpRequest类型的对象,相当于打开一个浏览器
var xhr = new XMLHttpRequest()
// 打开一个网址之间的连接
xhr.open('GET','##.php')
// 通过连接发送一次请求
xhr.send(null)
// 指定xhr状态变化事件处理函数
xhr.onreadystatechange = function() {// 通过xhr 的readyState判断请求的响应if(this.readyState === 4){console.log(this);}
}
复制代码
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'xxx.php')
xhr.send(null)
xhr.onload=function(){console.log(this.readyState)console.log(this.responseText)
}
</script>
复制代码
http
协议:
<script>
var xhr = new XMLHttpRequest()
xhr.open('GET', '/##.php') // 设置请求行
// xhr.setRequestHeader('HH', 'DA') // 设置一个请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('key=value&key1=value1') // 设置请求体
复制代码
<body><form action="##.php" method="post"><input type="text" name="name" id=""><button>提交</button></form>
</body>
复制代码
// http
// 设置请求报文的请求行
xhr.open('GET', './###.php')
// 设置请求头
xhr.setRequestHeader('Accept', 'text/plain')
// 设置请求体
xhr.send(null)xhr.onreadystateChange = function() {if(this.readyState === 4) {// 获取响应状态码console.log(this.status)// 获取响应状态描述console.log(this.statusText)// 获取响应头信息 // 获取指定响应头console.log(this.getResponseHeader('Content-Type'))// 获取全部响应头console.log(this.getAllResponseHeader())// 获取响应体// 获取响应文本形式console.log(this.responseText) // 获取xml形式console.log(this.responseXML)}
}
复制代码
进行初始化,建立连接,接收响应,响应体加载,加载成功!
// get请求
var xhr = new XMLHttpRequest()
xhr.open('GET', '.##.php?id=1')
// 一般get请求无需设置响应体
xhr.send(null);
xhr.onreadystatechange = function(){if(this.readyState === 4) {console.log(this.responseText);}
}
复制代码
// post
if(empty($_GE['id])) {$json = json_encode($data);echo $json;
}else{foreach($data as $item) {if($item['id'] != $_GET['id'] continue;$json = json_encode($data);echo $json;}
}
复制代码
异步的 JavaScript
和 XML
AJAX = Asynchronous JavaScript and XML
复制代码
用于创建快速动态网页的技术 XMLHttpRequest
对象
var xhr;
if (window.XMLHttpRequest){xhr=new XMLHttpRequest();}
else{xhr=new ActiveXObject("Microsoft.XMLHTTP");}
复制代码
向服务器发送请求
xmlhttp.open("GET","123.txt",true);
xmlhttp.send();
复制代码
请求类型,为get
和post
,url
文件在服务器上的位置,true
异步和false
同步。
xhr.open("POST","###.asp",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("name=da&age=12");
复制代码
onreadystatechange
事件 XMLHttpRequest
的状态信息,从0到4变化,0为请求未初始化,1为建立连接成功,2为请求已接收,3为请求处理中,4为请求完成。
xhr.onreadystatechange=function() {if (xhr.readyState==4 && xhr.status==200) {}}
复制代码
<ul id="list"></ul>var listElement = document.getElementById('list');var xhr = new XMLHttpRequest();
xhr.open('GET', '###。php?id=2');
xhr.send(null)
xhr.onreadystatechange = function() {if(this.readyState != 4) return// console.log(this.responseText)var data = JSON.parse(this.responseText)for(var i = 0; i<data.length; i++) {var liElement = document.createElement('li');liElement.innerHTML = data[i].name;listElement.appendChild(liElement);}
}
复制代码
xhr.onreadystatechange = function() {if(this.readyState != 4) returnvar data = JSON.parse(this.responseText)for(var i = 0; i<data.length; i++){var liElement = document.createElement('li')liElement.innerHTML = data[i].name;liElement.id=data[i].idlistElement.appendChild(liElement);liElement.addEventListener('click', function() {var xhr1 = new XMLHttpRequest();xhr1.open('GET', '###.php?id=' + this.id)xhr1.send()xhr1.onreadystatechange = function() {if(this.readyState != 4) returnvar obj = JSON.parse(this.responseText)alert(obj.age)}}}
}
复制代码
onreadystatechange
事件 readyState
返回当前请求的状态 responseBody
将回应信息文体 status
返回当前请求的状态码 statusText
返回当前请求的响应的状态 abort
取消当前请求 getAllResponseHeaders
获取响应指定的http
头 open
创建一个新的http
请求 send
发送请求到http
服务器并接收回应 setRequestHeader
指定请求头
<?php
if(empty($_POST['username']) || empty($_POST['password'])) {exit('请输入用户名和密码');
}
// 校验
$username = $_POST['username'];
$password = $_POST['password'];
if($username === 'admin' && $password === '123') {exit('成功');
}exit('失败');
?>
复制代码
var btn = document.getElementById('btn');
// 获取元素
var txtUsername = document.getElementById('username');
var textPassword = document.getElementById('password');
btn.onclick = function() {var username = txtUsername.value;var password = txtPassword.value;var xhr = new XMLHttpRequest();xhr.open('POST', '##.php');xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')// xhr.send('username=' + username + '&password=' + password)xhr.send(`username=${username}&password=${password}`);// 界面xhr.onreadystatechange = function() {if(this.readyState != 4) returnconsole.log(this.responseText);}
}
复制代码
// jquery中的ajax
$.ajax({type: 'GET',url: "###.php?id="+$('#id').val(),dataType: "json"success: function(data){$("jq").html();}else{$("jq").html();},error: function(jq) {alert();}
})
复制代码
$.ajax({ type: "POST",url: "ajax.php", dataType: "json", data: {"username": "admin","password": 123}, success: function(msg) { console.log(msg) }, error: function() { console.log("error") }
})
复制代码
function creathttprequest(){if(window.XMLHttpRequest)var xml=new XMLHttpRequest();elsevar xml=ActiveXObject("Miscrosoft.XMLHTTP");return xml;
}function addAjax() {var xml = createhttprequest();xml.open("POST","123.php",false); xml.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xml.send(url);if( xml.readyState == 4 && xml.status == 200 ) {alert(xml.responseText);}
}
复制代码
响应数据
<?phpheader('Content-Type: application/xml');
?><?xml version="1.0" encoding="utf-8"?>
<person><name>dashu</name><age>16</age><gender>男</gender>
</person>
复制代码
<script>
var xhr = new XMLHttpRequest()
xhr.open('GET', '###.php')
xhr.send()
xhr.onreadystatechange = function() {if(this.readyState != 4) return// console.log(this.responseXML)
// console.log(this.responseXML.documentElement.getElementsByTagName('name')[0])// console.log(this.responseXML.documentElement.children[0].innerHTML)
}
复制代码
如何解析服务端的数据:
<table><tbody id="content"></tbody>
</table><script>var xhr = new XMLHttpRequest()xhr.open('GET', '###.php')xhr.send()xhr.onreadystatechange = function() {if(this.readyState != 4) returnvar res = JSON.parse(this.responseText);var data = res.datafor(var i = 0; i<data.length; i++) {var tr = document.createElement("tr");var td = document.createElement("td");td.innerHTML = data[i].id;}}
</script>
复制代码
兼容:
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
复制代码
模板:
https//aui.github.io/art-template/
复制代码
面试手写:
var xhr = new XMLHttpRequest();xhr.open('GET', '###.php');xhr.send(null);xhr.onreadystatechange = function() {if(this.readyState === 4){console.log(this);}}
复制代码
实例:
<script>
function add(){var xhr;if (window.XMLHttpRequest){xhr=new XMLHttpRequest();}else{xhr=new ActiveXObject("Microsoft.XMLHTTP");}xhr.onreadystatechange=function(){if (xhr.readyState==4 && xhr.status==200){document.getElementById("div").innerHTML=xhr.responseText;}}xmlhttp.open("GET","/info.txt",true);xmlhttp.send();
}
</script>
复制代码
实例:
<script>function change(str){if(str == ""){document.getElementById("txt").innerHTML="";return;}if(window.XMLHttpRequest){xhr=new XMLHttpRequest();}else{xhr=new ActiveXObject("Microsoft.XMLHTTP");}xhr.onreadystatechange=function(){if (xhr.readyState==4 && xhr.status==200){document.getElementById("txt").innerHTML=xhr.responseText;}}xhr.open('GET','###.php?id=' + str, true);xhr.send();}
</script><form><select name="users" onchange="change(this.value"><option value=""></option><option value="1"></option><option value="2"></option></select>
</form><div id="txt"></div>//php$id = isset($_GET["id"]) ? intval($_GET["id"]) : '';$con = mysqli_connect('localhost','root','123456');if (!$con)
{die('连接失败: ' . mysqli_error($con));
}// 选择数据库
mysqli_select_db($con,"test");// 设置编码
mysqli_set_charset($con, "utf8");$sql="SELECT * FROM Websites WHERE id = '".$id."'";$result = mysqli_query($con,$sql);
复制代码
结言
好了,欢迎在留言区留言,与大家分享你的经验和心得。
感谢你学习今天的内容,如果你觉得这篇文章对你有帮助的话,也欢迎把它分享给更多的朋友,感谢。
作者简介
达叔,理工男,简书作者&全栈工程师,感性理性兼备的写作者,个人独立开发者,我相信你也可以!阅读他的文章,会上瘾!,帮你成为更好的自己。长按下方二维码可关注,欢迎分享,置顶尤佳。