网络知识 娱乐 Ajax前后端交互

Ajax前后端交互

Ajax前后端交互

通过表单的形式进行前后端的交互,首先创建一个文件夹,打开终端执行npm init
再npm install express npm install multer,在文件夹创建index.js 文件和public文件夹下面创建index.html 如图
在这里插入图片描述
现在再html中写Ajax请求:
1、创建一个XMLHttpRequest对象
ie浏览器中创建方式:var xhr = new ActiveXObject(“Microsoft.XMLHTTP”);
Netscape浏览器中创建方式为: var xhr=new XMLHttpRequest()
2、创建HTTP请求
XMLHttpRequest.open(method,URL,async,name,password);
method:请求的类型:GET 还是 POST
url:服务器(文件)位置,可以是绝对路径或是相对路径
async:true(异步)或 false(同步),默认为true。
name:该参数为可选参数,用于输入用户名。如果服务器需要验证,则必须使用该参数。
password:该参数为可选,用于输入密码。若服务器需要验证,则必须使用该参数。
注意:Netscape浏览器中使用open()方法只能打开与HTML文件在同一个服务器上的文件。而在IE浏览器中则无此限制(虽然可以打开其他服务器上的文件,但也会有警告提示)。
3、设置响应HTTP请求状态变化的函数
XMLHttpRequest.onreadystatechange = function() {}
onreadystatechange 属性定义当 readyState 发生变化时执行的函数。
readyState:保存了 XMLHttpRequest 的状态。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 正在处理请求
4: 请求已完成且响应已就绪
4、设置获取服务器返回数据的语句
status
200: “OK”
403: “Forbidden”
404: “Page not found”
statusText:返回状态文本(例如 “OK” 或 “Not Found”)
如果XMLHttpRequest对象的readyState属性值等于4,表示异步调用过程完毕,但是,异步调用过程完毕,并不代表异步调用成功了,如果要判断异步调用是否成功,还要判断XMLHttpRequest对象的status属性值,只有该属性值为200,才表示异步调用成功。
5、发送请求
XMLHttpRequest.send(data); post请求
XMLHttpRequest.send();get请求

完整的前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>form 请求</title>
    
</head>
<body>
    <button onclick="form1()">form请求</button>
   <div id="data">data</div>
    <script>
        function form1(){
            var xhr
            if(window.ActiveXObject){
                xhr=new ActiveXObject("Microsoft.XMLHTTP")
            }else{
                xhr=new XMLHttpRequest()
            }
            xhr.open('post','/home')
            xhr.onreadystatechange = function(){
                console.log('请求过程', xhr.readyState)
            if(xhr.readyState == 4)
            {
                console.log('请求状态码',xhr.status)
                if(xhr.status==200){
                    console.log(xhr.responseText)
                    document.getElementById("data").innerHTML=xhr.responseText
                }else{
                    console.log(xhr.status)
                }
            }
         }
         //表单发送的数据
            var form=new FormData()
            form.append('name','小王')
            form.append('age','25')
            form.append('sex','female')
            xhr.send(form)
        }

    </script>
</body>
</html>

服务器代码:写在index.js中

var express = require('express')

var bodyParser = require('body-parser')

// 如果使用的是FormData这种数据提交方式的话

// 那么需要multer里面的array()方法进行数据剥离

var multer = require('multer')

var web = express()

var form = multer()

web.use(express.static('public'))

web.use(bodyParser.urlencoded({extended:false}))

// req是前端给后端发送的数据时使用

// res是后端给前端发送数据时使用

web.post('/home',form.array(),function(req,res){

n = req.body.name

age = req.body.age

sex = req.body.sex

//给前端发送数据过去。

res.send('姓名是'+n+',年龄是'+age+',性别是'+sex)
//res.send(req.body)

})

// 创建本地服务器

web.listen('8080',function(){

console.log('服务器启动')

})

终端执行 node index.js在浏览器打开http://localhost:8080/
页面如下:
在这里插入图片描述
点击按钮后,页面数据更新:
在这里插入图片描述
控制台输出为:
在这里插入图片描述