ajax、FormData、fetch的使用

ajax、FormData、fetch的使用

本地使用Nodejs模拟服务器响应

使用nodejs简单实现服务器响应ajax请求,返回json数据,注意:ajax存在请求跨域问题,主要是因为浏览器响应机制,只会响应同一个域名下的文件,默认不同域的响应会忽略处理,因此需要再服务器设置响应头中设置相关配置

  • nodejs中设置
     res.setHeader('Access-Control-Allow-Origin','*');
     res.setHeader('Access-Control-Allow-Headers',"x-requested-with, content-type");
    
  • php中设置
    header("Access-Control-Allow-Origin:*");
    header('Access-Control-Allow-Methods:POST');
    header('Access-Control-Allow-Headers:x-requested-with, content-type');

代码实现:

const http = require('http');
const multiparty = require('multiparty');

http.createServer((req,res)=>{
    res.setHeader('Access-Control-Allow-Origin','*');
    res.write(JSON.stringify({code:200,msg:"sucess"}));
    res.end();
}).listen(8888,()=>{
    console.log('Server 8888 running');
})http.createServer((req,res)=>{
    res.setHeader('Access-Control-Allow-Origin','*');
    res.setHeader('Access-Control-Allow-Headers',"x-requested-with, content-type");

    let option = {
        autoFiles:true,
        uploadDir:'./20191226/upload'
    }
    let form = new multiparty.Form(option);
    form.parse(req);

    form.on('field',(name,value)=>{
        console.log("field:",name,value);
    })

    form.on('file',(name,file)=>{
        console.log("file:",name,file);
    })

    form.on("close",()=>{
        console.log('upload completed');
        res.write(JSON.stringify({code:200,msg:"sucess"}));
        res.end();
    })

    form.on("error",(err)=>{
        console.log('upload error');
        res.write(JSON.stringify({code:200,msg:err}));
        res.end();
    })


}).listen(8888,()=>{
    console.log('Server 8888 running');
})


XMLHttpRequest实现ajax请求

代码实现:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <script>
        window.onload = ()=>{
            let btn = document.getElementById('btn');
            btn.onclick = ()=>{
                let xhr = new XMLHttpRequest();
                xhr.open('GET','http://127.0.0.1:8888',true);//第三个参数默认为true异步请求,false为同步请求,目前已废弃
                xhr.send();//发送请求,如果为POST提交时,可以通过send()参数进行发送

                xhr.onreadystatechange = ()=>{
                    if(xhr.readyState==4){//已成功发送请求
                        if(xhr.status>=200&&xhr.status<300||xhr.status==304){
                            // alert("请求成功");
                            let result = JSON.parse(xhr.responseText);
                            console.log(result)    
                        }else{
                            alert("请求失败!");
                        }

                    }
                }
                
            }
        }
    </script>

</head>
<body>
    <input type="button" value="ajax请求测试" id="btn">
</body>

</html>

jquery实现ajax请求

jquery中提供多种发起ajax请求的方式,常用有 . a j a x 、 .ajax、 .ajax.post、$.get方式

代码实现:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>

    <script>
        $(function(){
            $(document).on('click','#btn',()=>{
                let list = {};
                $.ajax({
                    type:"POST",//请求方式
                    contentType:"application/json;charset=UTF-8",//请求类型
                    url:"http://127.0.0.1:8888",//请求地址
                    data:JSON.stringify(list),//请求数据
                    success:result=>{
                        console.log(JSON.parse(result));
                        return JSON.parse(result);
                    },//请求成功
                    error:err=>{
                        console.log(err.status);
                        console.log(err.responseText);
                    }
                });

            })
        })
    </script>
</head>
<body>
    <input type="button" value="ajax请求测试" id="btn">
</body>

</html>

fetch实现ajax请求

ES6中新增,用法简单

代码实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <script>
        window.onload = ()=>{
            let btn = document.getElementById('btn');
            btn.onclick = ()=>{
                var req = new Request("http://127.0.0.1:8888",{method:'POST',cache:'reload'});
                fetch(req)
                .then(response=>{
                    return response.json();
                }).then(data=>{
                    console.log(data);
                })
                .catch(err=>{
                    console.log(err);
                })
            }
        }

    </script>
</head>
<body>
    <input type="button" value="ajax请求测试" id="btn">
</body>

</html>

formData

代码实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        window.onload = function(){
            let myForm = document.getElementById('myForm'); 
            myForm.onsubmit = function(){
                let formData = new FormData(myForm);
                let xhr =new XMLHttpRequest();
                xhr.open(myForm.method,myForm.action,true);
                xhr.send(formData);
                xhr.onreadystatechange = ()=>{
                    if(xhr.readyState==4){//已成功发送请求
                        if(xhr.status>=200&&xhr.status<300||xhr.status==304){
                            alert("请求成功");
                            let result = JSON.parse(xhr.responseText);
                            console.log(result)    
                        }else{
                            alert("请求失败!");
                        }

                    }
                }

                return false;
            
            
            }
                
        }
    </script>    

</head>
<body>
    <form id="myForm" action="http://127.0.0.1:8888" method="POST" enctype="multipart/form-data">
        姓  名:<input type="text" name="username"><br>
        密  码:<input type="password" name="password"><br>
        附  件:<input type="file" name="file" id=""><br>
        <input type="submit" value="ajax请求测试" id="btn">
    </form>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值