会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132462个问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>07_Ajax的简单封装</title>
</head>
<body>
    <h1>07_Ajax的简单封装</h1>
    <input type="button" value="测试get" onclick="test01()"/>
    <input type="button" value="测试post" onclick="test02()"/>
    <script>
        function ajax(options){
            var xhr=new XMLHttpRequest()
            var params=''
            
            //带参数 遍历参数
            for(var atr in options.data){
                //进行拼接
                params=params+atr+'='+options.data[atr]+'&'
            }
            params=params.substr(0,params.length-1)
            if (options.type=='get'){
                options.url=options.url+"?"+params
            }
            xhr.open(options.type,options.url)
            if (options.type=='post'){
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
                xhr.send(params)
            }else{
                xhr.send()
            }
           
            xhr.onreadystatechange=function(){
                if(xhr.readyState==4 && xhr.status==200){
                    console.log(xhr.responseText)
                }
            }
        }

        function test01(){
            ajax({
                type:'get',
                url:'/login',
                data:{'name':'吕小布','pwd':123}

            })
        }
        function test02(){
            ajax({
                type:'post',
                url:'/login',
                data:{'name':'吕小布','pwd':123}

            })
        }
    </script>
</body>
</html>

老师 这句代码是有什么作用

var params=''

这个拼接 options.data[atr] 这个为什么就是字典的值 

params=params+atr+'='+options.data[atr]+'&'

如果是post请求 这个是固定的写法吗

if (options.type=='post'){
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
                xhr.send(params)


Python 全系列/第七阶段:网页编程基础/Ajax 9244楼
Python 全系列/第二阶段:Python 深入与提高/模块 9245楼
大数据全系列/第一阶段:Linux 操作系统/Linux常用命令 9246楼
WEB前端全系列/第十九阶段:Vue3企业级项目/Vue3企业级项目 9248楼
人工智能/第七阶段:机器学习-无监督学习(旧)/PCA降维算法 9249楼
Python 全系列/第一阶段:Python入门/编程基本概念 9250楼
WEB前端全系列/第二十阶段:Git版本控制器/Git版本控制器 9251楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 9253楼
Python 全系列/第五阶段:数据库编程/python操作mysql 9254楼
Python 全系列/第十二阶段:Python_Django3框架/Django初级 9255楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637