Web前端-Ajax基础技术(上)
2023-09-11 14:16:53 时间
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); // 1
xhr.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) return
var 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].id
listElement.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) return
var 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) return
console.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();
else
var 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);
}
}
响应数据
<?php
header('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) return
var res = JSON.parse(this.responseText);
var data = res.data
for(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);
结言
好了,欢迎在留言区留言,与大家分享你的经验和心得。
感谢你学习今天的内容,如果你觉得这篇文章对你有帮助的话,也欢迎把它分享给更多的朋友,感谢。
作者简介
达叔,理工男,简书作者&全栈工程师,感性理性兼备的写作者,个人独立开发者,我相信你也可以!阅读他的文章,会上瘾!,帮你成为更好的自己。长按下方二维码可关注,欢迎分享,置顶尤佳。
相关文章
- 触摸屏技术及其技巧解析
- 【华为云技术分享】从软件开发到 AI 领域工程师:模型训练篇
- Docker 基础技术之 Linux namespace 源码分析
- 【云栖大会】软件供应链革命:容器技术
- 数据挖掘技术
- SAP Spartacus 4.0 的技术变化
- Atitit nlp用到的技术与常见类库 目录 1. 常用的技术1 1.1. 语言处理基础技术 分词 相似度等1 1.2. 新闻摘要2 1.3. 情感倾向分析2 1.4. 文章标签2 1.
- Atitit web 3.0(web技术)展望与实现 和语义网络 目录 1. 为了说明Web 3.0,我们需要回顾Web历史上的重要浪潮。2 1.1. 2.Web 2.0:任何人可以参与。Web
- atitit 商业项目常用模块技术知识点 v3 qc29
- Unity技术手册-UGUI零基础详细教程-Text文本(打字、阴影、渐变)
- Unity技术手册 - 粒子基础主模块属性-上
- 全套Python零基础学习资料,电子书整理好了,想要进行技术提升,转行的自取!
- AI:大力出奇迹?Bigger is better?AI下一代浪潮?预训练大语言模型的简介(起源/目的/概述/技术基础/核心/影响/优缺点/未来趋势)、发展史、模型分类及其对比、案例应用之详细攻略
- Interview之AI:人工智能领域岗位求职面试—人工智能算法工程师知识框架及课程大纲(AI基础之数学基础/数据结构与算法/编程学习基础、ML算法简介、DL算法简介)来理解技术交互流程
- 【评论分享有礼】毕业遇上疫情怎么办?4条技术指南轻松应对(内含求职、租房攻略)
- 【华为云技术分享】ARM体系结构基础(3)
- m基于matlab的DQPSK调制解调技术的仿真
- 【技术写作】怎样通过技术写作实现财富自由?
- 0基础转行学软件测试,哪些技术是必须要掌握的?
- 【计算机三级数据库技术】第13章 大规模数据库架构--附思维导图
- Oracle的学习心得和知识总结(五)|Oracle数据库 Connect By 技术详解
- [SSD固态硬盘协议 6] NVME 2.0 新技术解决了什么痛点? 会带来哪些变革?
- 那些年我们一起追过的技术和开源软件