Web前端-Ajax基础技术(上)

Web前端-Ajax基础技术

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;
 }
}

异步的 JavaScriptXML

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();

请求类型,为getposturl文件在服务器上的位置,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);

结言

好了,欢迎在留言区留言,与大家分享你的经验和心得。

感谢你学习今天的内容,如果你觉得这篇文章对你有帮助的话,也欢迎把它分享给更多的朋友,感谢。

作者简介

达叔,理工男,简书作者&全栈工程师,感性理性兼备的写作者,个人独立开发者,我相信你也可以!阅读他的文章,会上瘾!,帮你成为更好的自己。长按下方二维码可关注,欢迎分享,置顶尤佳。

努力努力再努力Jeskson

posted @ 2019-03-10 18:28  达达前端  阅读(284)  评论(0编辑  收藏  举报