【前端工程师之ajax基础】原生XML请求+jquery发请求+axios发起请求

1.报文格式

请求报文和响应报文

1.1请求报文:

  • 请求行【POST URL,HTTP/2.1协议版本】
  • 请求头:一组组键值对
  • -请求体:一般POST请求才有,在浏览器调试工具的form data或者request payload 中看

1.2响应报文:

  • 响应行【HTTP/2.1协议版本,200状态码,ok响应报文】
  • 响应头:一组组键值对 响应体:服务器返回到JSON数据对象,在浏览器调试工具的response中看

2.express的使用

  • 初始化node项目 【npm init】
  • 安装express框架【npm i express】
  • 导入express【require(‘express’)】
  • 写代码…创建服务器
  • 启动服务器[node xxx.js]

3.原生ajax的基本操作

3.1分步走

 // 发起ajax请求
        // 1.创建XHR对象
        const xhr=new XMLHttpRequest();
        // console.log(xhr)
        // 2.初始化,请求方式和请求地址和请求参数
        xhr.open('GET','http://127.0.0.1:8000/server?studentName=mulan&age=18')
        // 3.发送
        xhr.send()
        // 4.事件绑定  ,处理服务端返回的结果
        // on       当什么时候
        // redayState       xhr对象的一个属性  值是0-4,4代表全部数据响应完毕
        // change           发生改变
        xhr.onreadystatechange=function(){
            if(xhr.readyState===4){
                // 2xx状态码表示响应成功
                if(xhr.status>=200 &xhr.status<300){
                    // 状态码,状态字符串
                     console.log(xhr.status,xhr.statusText)
                    // 所有响应头
                    // console.log(xhr.getAllResponseHeaders())
                    // 响应体
                    result.innerHTML=xhr.response
                }
               
            }else{

            }

        }

3.2其他情况

        // 设置请求头信息
        xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
         // 设置响应体数据类型
        xhr.responseType="json"
        // 自定义请求头信息
        xhr.setRequestHeader('user','mulan')
        // 设置请求延迟时间  2s
        xhr.timeout=2000
        // 绑定请求延时时间
        xhr.ontimeout=function(){
            alert('请求超时')
        }
        // 绑定请求异常时间
        xhr.onerror=function(){
            alert('网络似乎出了点小问题')
        }
        // 取消请求
        xhr.abort()

4.使用jqury发起请求

4.1get请求方式


// url,params,callback
  $.get('http://127.0.0.1:8000/jquery-server',{a:1,b:2},function(data){
     console.log(data)
  },'json')

4.2post请求方式

// url,data,callback
   $.post('http://127.0.0.1:8000/jquery-server',{user:'mulan',password:'123456'},function(data){
     console.log(data)
   })

4.3ajax请求方式


           $.ajax({
                    // 请求方式
                    method:'POST',
                    // url
                    url:'http://127.0.0.1:8000/jquery-server',
                    // 请求体
                    data:{
                        user:'mulan',
                        password:'123456'
                    },
                    
                    // 自定义设置请求头信息
                    headers:{
                        a:1,
                        b:2
                    },
                    // 响应体类型
                    dataType:'json',
                    // 设置响应最长时间
                    timeout:2000,
                    success:function(data){
                        console.log(data)
                    },
                    // 失败的回调
                    error(){
                        alert('请求失败')
                    }
                })

5.使用axios发起请求

//通用方法
       axios({             
                method:'POST',
                // url 路径
                url:'http://127.0.0.1:8000/axios-server',
                //  请求体
                data:{
                    username:'admin',
                    password:'admin'
                },
                // 请求头
                headers:{
                    weight:100,
                    height:180
                }

            }).then(value=>{
                console.log(value)
            })

            

        axios({             
                method:GET',
                // url 路径
                url:'http://127.0.0.1:8000/axios-server',
                // 查询字符串参数
                params:{
                    id:400,
                    vip:60
                },      
                // 请求头
                headers:{
                    weight:100,
                    height:180
                }

            }).then(value=>{
                console.log(value)
            })
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个基于Axios、Vue和TypeScript的封装的Ajax请求示例: ```typescript import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'; import { Vue } from 'vue-property-decorator'; // 定义全局配置 axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.timeout = 5000; // 定义请求拦截器 axios.interceptors.request.use((config: AxiosRequestConfig) => { // 在请求送前做一些处理,例如添加token等 const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; }, (error) => { return Promise.reject(error); }); // 定义响应拦截器 axios.interceptors.response.use((response: AxiosResponse) => { // 在响应返回后做一些处理,例如判断是否登录失效等 const data = response.data; if (data.code === 401) { Vue.prototype.$message.error('登录失效,请重新登录!'); localStorage.removeItem('token'); location.href = '/login'; } return response; }, (error) => { return Promise.reject(error); }); // 定义请求方法 export const ajax = { get<T>(url: string, params?: any): Promise<T> { return axios.get(url, { params }).then((res: AxiosResponse) => res.data); }, post<T>(url: string, data?: any): Promise<T> { return axios.post(url, data).then((res: AxiosResponse) => res.data); }, put<T>(url: string, data?: any): Promise<T> { return axios.put(url, data).then((res: AxiosResponse) => res.data); }, delete<T>(url: string, params?: any): Promise<T> { return axios.delete(url, { params }).then((res: AxiosResponse) => res.data); } }; ``` 使用时可以直接引入`ajax`对象调用相应的请求方法: ```typescript import { ajax } from './ajax'; // 送GET请求 ajax.get('/users', { page: 1, limit: 10 }).then((data) => { console.log(data); }).catch((error) => { console.error(error); }); // 送POST请求 ajax.post('/users', { name: '张三', age: 18 }).then((data) => { console.log(data); }).catch((error) => { console.error(error); }); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值