Código nativo AJAX (principio subyacente):
<script>
//js中问题的解决方案:console.log(),debugger,排除法
function doAjaxStart(){
debugger //js中断点
// console.log("==doAjaxStart()==")
//初始化span标记内部内容(可选)
let span=document.getElementById("result");
span.innerHTML="Data is loading....."
//创建XHR对象
let xhr=new XMLHttpRequest();
//设置状态监听
xhr.onreadystatechange=function(){
//readyState==4表示服务端响应到客户端的数据已经接收完成
//status==200 表示服务端处理过程OK的,500表示异常
if(xhr.readyState==4&&xhr.status==200){
span.innerHTML=xhr.responseText;
}
}
const url="http://localhost/doAjaxStart";
//建立连接
xhr.open("GET",url,true);//true 表示异步
//发送请求
xhr.send(null);
//console.log("==main==")
}
</script>
Solicitud nativa de obtención, publicación, eliminación y actualización
<script>
//更新
function doAjaxPut(){
//1.创建XHR对象
let xhr=new XMLHttpRequest();
//2.设置状态监听
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
let div=document.getElementById("result");
div.innerHTML=xhr.responseText;
}
}
}
//3.建立连接
let params="id=101&city=tianjin"
xhr.open("put",`http://localhost/doAjaxPut`,true);
//put请求必须要设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4.发送请求
xhr.send(params);//put请求可以将参数放到send方法内部
}
function doAjaxDelete(){
debugger
//1.创建XHR对象
let xhr=new XMLHttpRequest();
//2.设置状态监听
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
let div=document.getElementById("result");
div.innerHTML=xhr.responseText;
}
}
}
//3.建立连接
//let params="b";
let params="102";
xhr.open("delete",`http://localhost/doAjaxDelete/${
params}`,true);
//4.发送请求
xhr.send(null);
}
function doAjaxPostJson(){
//1.创建XHR对象
let xhr=new XMLHttpRequest();
//2.设置状态监听
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
let div=document.getElementById("result");
div.innerHTML=xhr.responseText;
}
}
}
//3.建立连接
let params={
id:103,city:"xiongan"}
let paramsStr=JSON.stringify(params);//将json对象转换为json字符串
console.log("jsonStr",paramsStr);
xhr.open("post",`http://localhost/doAjaxPostJSON`,true);
//post请求必须要设置请求头
xhr.setRequestHeader("Content-Type","application/json");
//4.发送请求
xhr.send(paramsStr);//post请求可以将参数放到send方法内部
}
function doAjaxPost(){
//1.创建XHR对象
let xhr=new XMLHttpRequest();
//2.设置状态监听
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
let div=document.getElementById("result");
div.innerHTML=xhr.responseText;
}
}
}
//3.建立连接
let params="id=102&city=shenzhen"
xhr.open("post",`http://localhost/doAjaxPost`,true);
//post请求必须要设置请求头
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//4.发送请求
xhr.send(params);//post请求可以将参数放到send方法内部
}
function doAjaxGet(){
debugger
//1.创建XHR对象
let xhr=new XMLHttpRequest();
//2.设置状态监听
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
if(xhr.status==200){
let div=document.getElementById("result");
div.innerHTML=xhr.responseText;
}
}
}
//3.建立连接
//let params="b";
let params="";
xhr.open("Get",`http://localhost/doAjaxGet/${
params}`,true);
//4.发送请求
xhr.send(null);
}
</script>
Llame después de la encapsulación por JQuery:
Aunque esta sección es más complicada, es el código más flexible.Puede averiguar la función de esta sección de código de acuerdo con la configuración de los parámetros.
<script>
function doAjax(){
let requestUrl="/doAjaxGet";
let params="";
//$符号在这里代表jquery对象
//ajax({})为jquery种的一个ajax函数,底层封装了ajax请求过程
$.ajax({
url:requestUrl,//key必须为url
data:params,
//type:"GET",//可以省略,默认为Get请求
dataType:"text",//服务端响应到客户端的数据格式,默认为json
//async:true,//默认异步
//contentType:"application/json",//假如需要向服务端传递json串
success:function(result){
//callback 回调函数
console.log("result",result);
//JS原生写法
//document.querySelector("#result").innerHTML=result;
//Jquery种的封装简化写法
$("#result").html(result);
}
});
//假如服务端响应到客户端的数据为json格式字符串,底层会默认将其转换为json对象
}
</script>
Publicar, obtener solicitud en jquery
Nota: Si dice que el símbolo $ no existe, necesita reconstruir el proyecto. La razón es que jquery.js en estático no se ha importado correctamente.
<script>
function doLoad(){
let requestUrl="/doAjaxGet";
//load函数会在指定位置通过ajax方法加载数据,并将数据更新到这个位置
$("#result").load(requestUrl,function(){
//可选
console.log("==load complete==");//加载完成以后执行
});
}
function doPost(){
let requestUrl="/doAjaxPost";
let params="id=104&city=shijiazhuang";
$.post(requestUrl,params,function(result){
alert(result);
})
}
function doGet(){
let requestUrl="/doAjaxGet";
let params="";
$.get(requestUrl,params,function(result){
$("#result").html(result);
},"text");//默认为json
}
function doAjax(){
let requestUrl="/doAjaxGet";
let params="";
//$符号在这里代表jquery对象
//ajax({})为jquery种的一个ajax函数,底层封装了ajax请求过程
$.ajax({
url:requestUrl,//key必须为url
data:params,
//type:"GET",//可以省略,默认为Get请求
dataType:"text",//服务端响应到客户端的数据格式,默认为json
//async:true,//默认异步
//contentType:"application/json",//假如需要向服务端传递json串
success:function(result){
//callback 回调函数
console.log("result",result);
//JS原生写法
//document.querySelector("#result").innerHTML=result;
//Jquery种的封装简化写法
$("#result").html(result);
}
});
//假如服务端响应到客户端的数据为json格式字符串,底层会默认将其转换为json对象
}
</script>
<script>
var cityColumns=[{
title:"id"},{
title:"city"},{
title:"operation"}];
$(function(){
//页面加载完成以后执行
debugger
doInit("city-table",cityColumns);//创建thead,tbody
//异步加载服务端数据
doLoadCitys();
})
//异步加载服务端citys信息
function doLoadCitys(){
$.ajax({
url:"/doAjaxGet",
success(result){
//readyState==4 && status==200
//console.log(result);
doSetTableBodyRows($("#city-table>tbody"),result);
}
});
}
//将服务端响应的结果更新到页面table的tbody位置
function doSetTableBodyRows(tBody,result){
//清空tbody原有内容
tBody.empty();
//迭代服务端的响应结果,并将其追加到tbody
//方法1
// for(let i=0;i<result.length;i++){
// tBody.append(doCreateRow(result[i]));
// }
//方法2
// result.forEach(function(item) {
// tBody.append(doCreateRow(item));
// })
//方法3
result.forEach(item=>tBody.append(doCreateRow(item)));
}
function doCreateRow(row){
return `<tr>
<td>${
row.id}</td>
<td>${
row.city}</td>
<td><a href='javascript:doDeleteById(${
row.id})'>delete</td>
</tr>`
}
function doDeleteById(id){
$.ajax({
url:`/doAjaxDelete/${
id}`,
method:"delete",
success(result){
alert(result);
doLoadCitys();//刷新
}
})
}
</script>