Ajax基本使用

2020-08-17  本文已影响0人  攻城老狮

一. 初步使用

  1. 在服务器端初始化依赖
mkdir ajax-server
cd ajax-server
npm init
npm install express
  1. 在 ajax-server 目录下,新建名为 app.js 的文件,并写入如下内容
//引入模块
const express = require("express");
const path = require("path");
//创建web服务器
const app = express();
//静态资源访问服务功能
app.use(express.static(path.join(__dirname,"public")));
//处理 /first 的get请求
app.get('/first',(req,res)=>{
    res.send("Hello World");
});
//监听端口
app.listen(3000);
//控制台输出
console.log("服务器启动成功");
  1. 启动服务器
node app.js
  1. 测试 /first 路径是否可以成功访问
# 在浏览器地址栏中输入以下内容,测试是否可以正常输出 Hello World
http://62.234.149.220:3000/first
  1. 编写客户端的Ajax程序
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script type="text/javascript">
        //1.创建ajax对象
        var xhr = new XMLHttpRequest();
        //2.初始化ajax对象
        xhr.open("get","http://62.234.149.220:3000/first");
        //3.发送请求
        xhr.send();
        //4.获取响应数据
        xhr.onload =function(){
            console.log(xhr.responseText);
        }     
    </script>
</head>
<body>
</body>
</html>
  1. 测试

运行该页面即可在控制台获取到ajax请求得到的数据 Hello World

二. ajax基本使用

  1. 处理服务器返回的JSON数据

实例:由于传输过程中均使用的为string字符串类型,而该类型不方便操作,故需要我们在客户端接收到string类型的数据后使用window对象内置的方法将string类型的数据转换为JSON类型的数据,方便处理。

在之前程序的基础上,添加额外的get请求,返回json格式的字符串

const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname,"public")));
//发送json格式的字符串方法
app.get("/responseData",(req,res)=>{
    res.send({"name":"yorick","age":18});
});
app.listen(3000);
console.log("服务器启动成功");

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
         var xhr = new XMLHttpRequest();
        xhr.open("get","http://62.234.149.220:3000/responseData");
        xhr.send();
        xhr.onload =function(){
            var jsonData = JSON.parse(this.responseText);
            console.log(jsonData);
        };
    </script>
</head>
<body>
</body>
</html>

测试发现控制台输出的为Json类型的对象

  1. 请求参数传递

GET请求类型

实例:客户端当点击提交按钮后,触发AJAX的请求,将input标签中的参数拼接到url路径中,提交给服务打的处理程序。服务器端程序将请求参数原样返回给客户端。

服务器端程序

const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname,"public")));
//接收来自 /get的GET类型请求,并将请求参数原样返回
app.get("/get",(req,res)=>{
    res.send(req.query);
});
app.listen(3000);
console.log("服务器启动成功");

客户端程序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").on("click",function(){
                var xhr = new XMLHttpRequest();
                //获取input输入框的数据
                var username = $("#username").val();
                var age = $("#age").val();
                //拼接请求参数
                var params = "username="+username+"&age="+age;
                //将请求参数加入访问路径中
                xhr.open("get","http://62.234.149.220:3000/get?"+params);
                xhr.send();
                xhr.onload = function(){
                    console.log(this.responseText);
                };
            }); 
        });
    </script>
</head>

<body>
    用户名:<input type="text" id="username"/>
    年龄:<input type="text" id="age" />
    <input type="button" id="btn" value="提交" />
</body>
</html>

POST请求类型

实例:向服务端发送POST请求,并携带参数

服务端程序

const express = require("express");
const path = require("path");
//引入body-parser
const bodyParser = require("body-parser");
const app = express();
//设置bodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname,"public")));
//接收post请求
app.post("/post",(req,res)=>{
    res.send(req.body);
});
app.listen(3000);
console.log("服务器启动成功");

客户端程序

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").on("click",function(){
                var xhr = new XMLHttpRequest();
                var username = $("#username").val();
                var age = $("#age").val();
                var params = "username="+username+"&age="+age;
                xhr.open("post","http://62.234.149.220:3000/post");
                //上述params格式的数据传输,需要设置如下的内容类型
                xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                //通过send发送数据
                xhr.send(params);
                xhr.onload = function(){
                    console.log(this.responseText);
                };
            }); 
        });
    </script>
</head>

<body>
    用户名:<input type="text" id="username"/>
    年龄:<input type="text" id="age" />
    <input type="button" id="btn" value="提交" />
</body>
</html>

服务端代码

const express = require("express");
const path = require("path");
const bodyParser = require("body-parser");
const app = express();
//改为解析json类型
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,"public")));
app.post("/json",(req,res)=>{
    res.send(req.body);
});
app.listen(3000);
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            var xhr = new XMLHttpRequest();
            xhr.open("post","http://62.234.149.220:3000/json");
            //设置json类型
            xhr.setRequestHeader("Content-Type","application/json");
            //发送json前需要先转换为字符串类型
            xhr.send(JSON.stringify({name:"yorick",age:23}));
            xhr.onload = function(){
                console.log(this.responseText);
            };
        });
    </script>
</head>
<body>
</body>
</html>
  1. ajax状态码
# ajax状态码表示的是ajax请求的过程状态,与http状态码有所区别,后者为服务器发送的请求结果状态码
0 已经创建ajax对象,但没有对其进行配置
1 已经对ajax进行配置,但是没有发送请求
2 请求已经发送
3 已经接收到来自服务器端的部分数据
4 服务器端的响应数据已经接收完成

服务端代码

const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname,"public")));
app.get("/readyState",(req,res)=>{
    res.send("Finish");
});
app.listen(3000);
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            var xhr = new XMLHttpRequest();
            //0 已经创建ajax对象,但没有对其进行配置
            console.log(xhr.readyState);
            xhr.open("get","http://62.234.149.220:3000/readyState");
            //1 已经对ajax进行配置,但是没有发送请求
            console.log(xhr.readyState);
            xhr.onreadystatechange = function(){
                //2 请求已经发送
                //3 已经接收到来自服务器端的部分数据
                //4 服务器端的响应数据已经接收完成
                console.log(xhr.readyState);
                //当状态码为4,代表数据已经接收完成,可以输出
                if(xhr.readyState == 4){
                    console.log(xhr.responseText);
                }
            };
            xhr.send();
        });
    </script>
</head>
<body>
</body>
</html>
  1. ajax的错误处理
# 1.服务器端可接收到请求,但不是预期结果。可以在客户端判断返回的状态码进行处理
# 2.服务器没有接收到请求 404
# 3.服务器后端程序问题 500
# 4.网络中断,会触发xhr对象的onerror事件,在其中可对错误进行处理

实例:服务器返回400状态码,客户端通过判别,执行400状态码的处理语句。网络中断调用onerror事件

服务器端代码

const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname,"public")));
app.get("/error",(req,res)=>{
    res.status(400).send("400错误");
});
app.listen(3000);
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").click(function(){
                var xhr = new XMLHttpRequest();
                xhr.open("get","http://62.234.149.220:3000/error");
                xhr.send();
                xhr.onload = function(){
                    //获取返回的服务端报错信息
                    console.log(this.responseText);
                    //获取状态码
                    console.log(this.status);
                };
                //网络中断,触发onerror事件
                xhr.onerror = function(){
                    console.log("服务器中断");
                }
            });
        });
    </script>
</head>
<body>
    <button id="btn">发送请求</button>
</body>
</html>
  1. ajax的函数封装

实例:将ajax请求进行函数封装,以对象的形式指定请求方式,地址以及结果的回调函数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        function ajax(options) {
            var defaults = {
                type: "get",
                url: "",
                data: {},
                header: {
                    "Content-Type": "application/x-www-form-urlencoded"
                },
                success: function () { },
                error: function () { }
            }
            Object.assign(defaults,options);
            var xhr = new XMLHttpRequest();
            var params = "";
            $.each(defaults.data, function (key, value) {
                params += key + "=" + value + "&";
            });
            params = params.substr(0, params.length - 1);
            if (defaults.type == "get") {
                defaults.url = defaults.url + "?" + params;
            }
            xhr.open(defaults.type, defaults.url);
            if (defaults.type == "post") {
                var contentType = defaults.header["Content-Type"];
                xhr.setRequestHeader("Content-Type", contentType);
                if (contentType == "application/json") {
                    xhr.send(JSON.stringify(defaults.data));
                } else {
                    xhr.send(params);
                }
            } else {
                xhr.send();
            }
            xhr.onload = function () {
                var contentType = xhr.getResponseHeader("Content-Type");
                var responseText = xhr.responseText;
                if (contentType.includes("application/json")) {
                    responseText = JSON.parse(xhr.responseText);
                }
                if (this.status == 200) {
                    defaults.success(responseText, this);
                } else {
                    defaults.error(responseText, this);
                }

            };
        }

        ajax({
            type: "get",
            url: "http://62.234.149.220:3000/responseData",
            data: {
                name: "yorick",
                age: 23
            },
            header: {
                "Content-Type": "application/json"
            },
            success: function (data, xhr) {
                console.log(data);
                console.log(xhr);
            },
            error: function (data, xhr) {
                console.log(data);
                console.log(xhr);
            }
        });
        // ajax({
        //     url: "http://62.234.149.220:3000/responseData",
        //     success: function (data, xhr) {
        //         console.log(data);
        //         console.log(xhr);
        //     }
        // });
    </script>
</head>

<body>
</body>
</html>

三. FormData对象

  1. 使用FormData传递表单参数

服务端代码

const express = require("express");
const path = require("path");
const formidable = require("formidable");
const app = express();
app.use(express.static(path.join(__dirname,"public")));
app.post("/formData",(req,res)=>{
    //创建formidable表单解析对象
    const form = new formidable.IncomingForm();
    //解析传递过来的FormData对象
    form.parse(req,(err,fields,files)=>{
        res.send(fields);
    });
});
app.listen(3000);
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").click(function(){
                //将普通html表单转换为表单对象
                var formData = new FormData($("#form")[0]);
                var xhr = new XMLHttpRequest();
                //由于需将formData放入send方法中,故必须使用post提交方式
                xhr.open("post","http://62.234.149.220:3000/formData");
                xhr.send(formData);
                xhr.onload = function(){
                    if(this.status == 200){
                        console.log(this.responseText);
                    }
                };
            });
        });
    </script>
</head>

<body>
    <form id="form">
        <input type="text" name="username"/>
        <input type="password" name="password"/>
        <input type="button" id="btn" value="提交"/>
    </form>
</body>
</html>
  1. FormData对象中的实例方法
# 获取值
formData.get("key");
# 设置值,有该属性则替换值,没有则新添加值
formData.set("key","value");
# 删除值,服务器不会接收到passowrd属性
formData.delete("password");
# 追加值,与set的区别在于,当属性名存在时,set会覆盖属性值,append会保留两个值
formData.append("username","bob");

实例:在上述代码的基础上,获取username的属性值并且重新设置该值,添加新的age属性,删除password属性,追加已经存在的username属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").click(function(){
                var formData = new FormData($("#form")[0]);

                //获取username属性值
                console.log(formData.get("username"));
                //设置值
                formData.set("username","alice");
                formData.set("age",23);
                //删除值
                formData.delete("password");
                //追加值
                formData.append("username","bob");

                var xhr = new XMLHttpRequest();
                xhr.open("post","http://62.234.149.220:3000/formData");
                xhr.send(formData);
                xhr.onload = function(){
                    if(this.status == 200){
                        console.log(this.responseText);
                    }
                };
            });
        });
    </script>
</head>

<body>
    <form id="form">
        <input type="text" name="username"/>
        <input type="password" name="password"/>
        <input type="button" id="btn" value="提交"/>
    </form>
</body>
</html>
  1. FormData文件上传

服务端代码

const express = require("express");
const path = require("path");
const formidable = require("formidable");
const app = express();
app.use(express.static(path.join(__dirname,"public")));
app.post("/upload",(req,res)=>{
    const form = new formidable.IncomingForm();
    //添加文件上传的存储路径
    form.uploadDir = path.join(__dirname,"public","uploads");
    //保留后缀
    form.keepExtensions = true;
    form.parse(req,(err,fields,files)=>{
        res.send("ok");
    });
});
app.listen(3000);
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#file").change(function(){
                var formData = new FormData();
                //追加文件
                formData.append("attrName",this.files[0]);
                var xhr = new XMLHttpRequest();
                xhr.open("post","http://62.234.149.220:3000/upload");
                xhr.send(formData);
                xhr.onload = function(){
                    if(this.status == 200){
                        console.log(this.responseText);
                    } 
                };
            });
        });
    </script>
</head>

<body>
    <input type="file" id="file"/>
</body>
</html>

四. 同源问题

  1. 同源

若两个页面拥有相同的协议,域名和端口。那么这两个网页就属于同源。有一个不相同则不属于同源。

  1. JSONP解决同源问题
1.将不同源的服务器请求地址写在script标签的src属性上
2.服务器响应的数据必须是函数的调用,发送给客户端的数据需要作为函数调用的参数
3.在客户端全局作用域下定义函数
4.在该函数内部对服务器端返回的数据进行处理

实例:通过JSONP的方式请求不同源的服务器数据

服务端代码

//引入express框架
const express = require("express");
//路径处理模块
const path = require("path");
//创建web服务
const app = express();
//静态资源访问服务功能
app.use(express.static(path.join(__dirname,"public")));
//JSONP请求测试
app.get("/test",(req,res)=>{
    const result = "fun({name:'yorick'})";
    res.send(result);
});
//监听端口
app.listen(3000);
//控制台提示输出
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
</head>
<body>
    <script>
        function fun(data){
            console.log("客户端的fun函数被调用");
            console.log(data);
        }
    </script>
    <script src="http://62.234.149.220:3000/test"></script>
</body>
</html>
  1. JSONP优化

服务端代码

const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname,"public")));
//JSONP优化,根据客户端的要求动态改变调用的函数名
app.get("/better",(req,res)=>{
    // const funName = req.query.callback;
    // const params = JSON.stringify({name: 'alice',age: 22});
    // const result = funName + "("+ params +")";
    // res.send(result);
    res.jsonp({name:"bob",age: 18});
});
app.listen(3000);
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
</head>
<body>
    <button id="btn">发送请求</button>
    <script>
        $(function(){
            function jsonp(options){
                //动态创建script标签
                var script = document.createElement("script");
                //随机生成回调函数名
                var fnName = "myJsonp" + Math.random().toString().replace(".","");
                //拼接请求参数
                var params = "";
                for(var param in options.data){
                    params += "&" + param + "=" + options.data[param];
                }
                //将success的函数挂载到window对象中,变为全局函数
                window[fnName] = options.success;
                //由于script的src是get请求,故将回调函数和参数拼接到访问路径中
                script.src = options.url + "?callback=" + fnName + params;
                //将内存中的变量追加到body标签中,实现JSONP请求
                document.body.appendChild(script);
                //当加载完成删除该标签,防止重复添加
                script.onload = function(){
                    document.body.removeChild(script);
                };
            }
            
            $("#btn").click(function(){
               jsonp({
                   url: "http://62.234.149.220:3000/better",
                   data: {
                       name: "yorick",
                       age: 23
                   },
                   success: function(data){
                        console.log("客户端的fun函数被调用");
                        console.log(data);
                   }
               });
            });   
        });
    </script>
</body>
</html>
  1. CORS跨域资源共享解决同源问题,需要在服务器端设置两个响应头信息

服务端代码

const express = require("express");
const path = require("path");
const app = express();
app.use(express.static(path.join(__dirname,"public")));
//解决非同源请求问题
app.use((req,res,next)=>{
    res.header("Access-Control-Allow-Origin","*");
    res.header("Access-Control-Allow-Methods","get,post");
    next();
});
//get请求
app.get("/cross",(req,res)=>{
    res.send("ok");
});
app.listen(3000);
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script src="./ajax.js"></script>
    <script>
        $(function(){
            $("#btn").click(function(){
                ajax({
                    type: "get",
                    url: "http://62.234.149.220:3000/cross",
                    success: function(result){
                        console.log(result);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">提交请求</button>
</body>
</html>
  1. 跨域传递Cookie
# 1. 需要在客户端的ajax请求中添加
xhr.withCredentials = true;
# 2. 需要在服务器端添加响应头信息
res.header("Access-Control-Allow-Credentials",true);

五. JQuery对ajax的封装

  1. $.ajax()方法的使用

服务端代码

//引入express框架
const express = require("express");
//路径处理模块
const path = require("path");
//创建web服务
const app = express();
//静态资源访问服务功能
app.use(express.static(path.join(__dirname,"public")));

app.get("/first",(req,res)=>{
    res.send("Hello World");
});
//监听端口
app.listen(3000);
//控制台提示输出
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").on("click",function(){
                $.ajax({
                    type: "get",
                    url: "/first",
                    success: function(response){
                        console.log(response);
                    },
                    error: function(xhr){
                        console.log(xhr);
                    }
                });
            });
        });
    </script>
</head>
<body>
    <button id="btn">发送请求</button>
</body>
</html>
  1. $.ajax()方法的参数传递
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").on("click",function(){
                $.ajax({
                    //get 或者 post
                    type: "post",
                    url: "/post",
                    data: {
                        name: "yorick",
                        age: 22
                    },
                    //或者
                    //data: "name=yorick&age=22",
                    success: function(response){
                        console.log(response);
                    },
                    error: function(xhr){
                        console.log(xhr);
                    }
                });
            });
        });
    </script>
</head>

<body>
    <button id="btn">发送请求</button>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").on("click",function(){
                $.ajax({
                    type: "post",
                    url: "/json",
                    //指定类型
                    contentType: "application/json",
                    //转换json格式为字符串的形式
                    data: JSON.stringify({
                        name: "yorick",
                        age: 12
                    }),
                    success: function(response){
                        console.log(response);
                    },
                    error: function(xhr){
                        console.log(xhr);
                    }
                });
            });
        });
    </script>
</head>

<body>
    <button id="btn">发送请求</button>
</body>
</html>
  1. $.ajax()方法中beforeSend的使用
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").on("click",function(){
                $.ajax({
                    type: "post",
                    url: "/json",
                    contentType: "application/json",
                    data: JSON.stringify({
                        name: "yorick",
                        age: 12
                    }),
                    //请求发送前调用
                    beforeSend: function(){
                        alert("发送前对数据进行处理");  
                        //若return false 则不会发送数据  
                        return false;
                    },
                    success: function(response){
                        console.log(response);
                    },
                    error: function(xhr){
                        console.log(xhr);
                    }
                });
            });
        });
    </script>
</head>

<body>
    <button id="btn">发送请求</button>
</body>
</html>
  1. serialize()和serializeArray()方法

实例:通过serialize()方法将表单内容拼接为字符串类型的参数,通过自定义的serializeObject()方法将表单用户输入的内容转换为对象类型

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#form").on("submit",function(){
                //将表单内容拼接为字符串类型的参数
                var params = $(this).serialize();
                //username=yorick&password=123
                console.log(params);
                //将表单用户输入的内容转换为对象类型
                var paramsObj = serializeObject($(this));
                //{username: "yorick", password: "123"}
                console.log(paramsObj);
                //禁用默认行为
                return false;
            });

            //将表单用户输入的内容转换为对象类型
            function serializeObject(obj){
                var result = {};
                // [{name:"username",value:"yorick"},{name:"password",value:"123456"}]
                var params = obj.serializeArray();
                //遍历数组,变为 {username:"yorick",password:"123456"}
                $.each(params,function(index,value){
                    result[value.name] = value.value;
                });
                return result;
            }
        });
    </script>
</head>

<body>
    <form id="form">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="submit" value="提交">
    </form>
</body>
</html>
  1. 发送jsonp请求
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").on("click",function(){
                $.ajax({
                   url: "http://62.234.149.220:3000/jsonp",
                   //向服务端传递函数名字,将原先的callback换为自定义的cb
                   //jsonp: "cb",
                   //定义回调函数,此时需要在客户端自行定义fn函数,删除success回调函数
                   //jsonpCallback: "fn",
                   //代表发送jsonp请求
                   dataType: "jsonp",
                   success: function(response){
                       console.log(response);
                   } 
                });
            });
        });
    </script>
</head>

<body>
    <button id="btn">发送请求</button>
</body>
</html>
  1. .get()和.post()方法
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").on("click",function(){
                $.get("http://62.234.149.220:3000/get",{name:"alice",age:20},function(response){
                    console.log(response);
                });
                $.post("http://62.234.149.220:3000/post",{name:"bob",age:21},function(response){
                    console.log(response);
                })
            });
        });
    </script>
</head>

<body>
    <button id="btn">发送请求</button>
</body>

</html>
  1. ajax的全局事件
.ajaxStart()
.ajaxComplete()
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function(){
            $("#btn").on("click",function(){
                $.ajax({
                    type: "get",
                    url: "http://62.234.149.220:3000/get",
                    data: {
                        name: "Tom",
                        age: 21
                    },
                    success: function (response) {
                        console.log(response);
                    }
                });
            });
            //在document对象上绑定ajaxStart事件,在发送ajax请求前被调用
            $(document).on("ajaxStart",function(){
                console.log("start ajax...");
            });
            //在document对象上绑定ajaxComplete事件,在发送ajax请求后被调用
            $(document).on("ajaxComplete",function() {
                console.log("end ajax...");
            });
        });
    </script>
</head>

<body>
    <button id="btn">发送请求</button>
</body>

</html>
  1. restful风格的请求格式

服务器端代码

//引入express框架
const express = require("express");
//路径处理模块
const path = require("path");
//创建web服务
const app = express();
const bodyParser = require("body-parser");
const formidable = require("formidable");
//静态资源访问服务功能
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname,"public")));

app.get("/users",(req,res)=>{
    res.send("获取用户列表数据");
});
app.get("/users/:id",(req,res)=>{
    var id = req.params.id;
    res.send(`获取id为${id}的用户信息`);
});
app.delete("/users/:id",(req,res)=>{
    var id = req.params.id;
    res.send(`删除id为${id}的用户信息`);
});
app.put("/users/:id",(req,res)=>{
    var id = req.params.id;
    res.send(`修改id为${id}的用户信息`);
});

//监听端口
app.listen(3000);
//控制台提示输出
console.log("服务器启动成功");

客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.4.1 copy.js"></script>
    <script>
        $(function() {
            // get请求获取用户列表信息
            $.ajax({
                type: "get",
                url: "http://62.234.149.220:3000/users",
                success: function(response){
                    console.log(response);
                }
            });

            //get请求获取某个id用户的信息
            $.ajax({
                type: "get",
                url: "http://62.234.149.220:3000/users/10",
                success: function(response){
                    console.log(response);
                }
            });

            //deltet请求删除某个id用户的信息
            $.ajax({
                type: "delete",
                url: "http://62.234.149.220:3000/users/9",
                success: function(response){
                    console.log(response);
                }
            });

            //put请求修改某个id用户的信息
            $.ajax({
                type: "put",
                url: "http://62.234.149.220:3000/users/8",
                success: function(response){
                    console.log(response);
                }
            });

        });
    </script>
</head>
<body>
</body>
</html>
上一篇下一篇

猜你喜欢

热点阅读