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,
                    }
                })
    
  • 相关阅读:
    ror小记
    uuid before_create
    好东西jquery ui slider
    ror
    rails3 reventl
    ad
    wiki guide tutorial
    忽然意识到我需要端正态度
    20101022网站更新部署
    ECFA
  • 原文地址:https://www.cnblogs.com/liliuyu/p/12007057.html
Copyright © 2011-2022 走看看