zoukankan      html  css  js  c++  java
  • 封装原生js中ajax请求

    写一个函数方法,参数传入即可。默认get 请求

    function ajax(option){
                      var Method = option.method || "GET"
                        var data = option.data || {} // {pageNum:1, pageSize:10}
                        var url = option.url   // http://localhost:3000/api/film/getList
                        
                       if(Method == 'GET'){
                        var str = "?"
                        for(var key in data){
                            str += key + "=" + data[key] + "&" // pageNum=1pageSize=10
                        }
                        // 切除掉最后一个 & 
                        str = str.slice(0,str.length-1)
                        url +=str
                        }
                        // 将参数拼接到URL上
                        console.log(url)
                        // 1.创建ajax对象
                        var xhr = new XMLHttpRequest()
                        // 2.建立连接
                        xhr.open(Method, url,true)
                        // 3.发送请求
                        xhr.send()
                        // 4.监听数据回来
                        xhr.onreadystatechange=function(){
                            // xhr.readyState === 4 意味这服务器返回数据
                            // xhr.status == 200 服务器返回正确的数据
                             if( xhr.readyState === 4 && xhr.status == 200 ){
                                  
                                  var res =  JSON.parse(xhr.responseText)
                                    option.success(res)
                             }
                        }
                }
    

    ajax调用

                ajax({
                    url:"http://localhost:3000/api/film/getList",
                    success:function(res){
                         console.log(res)
                    },
                    method:"GET",
                    data:{
                        pageNum:1,
                        pageSize:10,
                    }
                })
    
  • 相关阅读:
    Unity-国际版下载
    Js数值处理
    Vue,部署通过Url指向dist里的index, 通过IIS 7.0及以上部署,添加 注册托管代码模块
    反编译
    Node 命令
    VUE开发命令
    VS2017发布到部署网站
    谷歌浏览器提示您的连接不是私密连接
    iis,配置
    VS开发android
  • 原文地址:https://www.cnblogs.com/liliuyu/p/12007057.html
Copyright © 2011-2022 走看看