WdnmDwcwq 2022-08-21 15:29 采纳率: 100%
浏览 25
已结题

ajax x-www-form-urlencoded

封装的ajax


function queryStringify(obj) {
  let str = ''
  for (let k in obj) str += `${k}=${obj[k]}&`

  //username=kerwin&password=789&
  return str.slice(0, -1)
}

// 封装 ajax
function ajax(options) {
  let defaultoptions = {
    url: "",
    method: "GET",
    async: true,
    data: {},
    headers: {},
    success: function () { },
    error: function () { }
  }
  let { url, method, async, data, headers, success, error } = {
    ...defaultoptions,
    ...options
  }

  // console.log(url, method, async, data, headers, success, error)

  if (typeof data === 'object' && headers["content-type"]?.indexOf("json") > -1) {
    data = JSON.stringify(data)
  }
  else {
    data = queryStringify(data)
  }
  // // 如果是 get 请求, 并且有参数, 那么直接组装一下 url 信息
  if (/^get$/i.test(method) && data) url += '?' + data
  
  // // 4. 发送请求
  const xhr = new XMLHttpRequest()
  xhr.open(method, url, async)
  xhr.onload = function () {
    if (!/^2\d{2}$/.test(xhr.status)) {
      // console.log(error)
      error(`错误状态码:${xhr.status}`) //回调
      return
    }

    // 执行解析


    try {
      let result = JSON.parse(xhr.responseText)
      success(result)
    } catch (err) {
      error('解析失败 ! 因为后端返回的结果不是 json 格式字符串')
    }
  }

  // console.log(22222)

  // // 设置请求头内的信息
  for (let k in headers) xhr.setRequestHeader(k, headers[k])
  if (/^get$/i.test(method)) {
    xhr.send()
  } else {
    xhr.send(data)
  }

  // xhr.send(data)
}


调用
```javascript
//x-www-form-urlencoded
ajax({
            url:"http://localhost:3000/users",
            method:"POST",
            data:"username=yyxx&password=123456&",
            headers:{
                "content-type":"application/x-www-form-urlencoded"
            },
            success:function(res){
                console.log("success",res)
            },
            error:function(error){
                console.log("error",error)
            }
        })
//json
ajax({
            url:"http://localhost:3000/users",
            method:"POST",
            data:{
                username:"y",
                password:"456"
            },
            headers:{
                "content-type":"application/json"
            },
            success:function(res){
                console.log("success",res)
            },
            error:function(error){
                console.log("error",error)
            }
        })

为什么使用x-www-form-urlencoded方式传入解析不了而json格式却可以

img

img

  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      问题事件

      • 已结题 8月21日
      • 已采纳回答 8月21日
      • 修改了问题 8月21日
      • 修改了问题 8月21日
      • 展开全部

      悬赏问题

      • ¥15 如何关闭soui dummy wdn 进程
      • ¥20 含有jar文件的文件夹用tar -zcvf 命令压缩后要怎么还原回去?
      • ¥15 天宝TBC软件出现报错怎么解决
      • ¥15 micropython 从1开始切片报错
      • ¥15 请问该怎么做才能将文字说明和二维码一起作为png图片一起下载
      • ¥15 r语言 混频数据回归 midas_r
      • ¥15 人脸识recogizer.predict返回值id报错,KeyError,详情如下
      • ¥15 geowebcache部署失败
      • ¥20 关于adaboost+haar特征实现人脸检测过程的一些细节问题
      • ¥15 csv文件增加一列 为csv文件的名字