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

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条回答 默认 最新

  • 林晓风 2022-08-21 15:37
    关注

    因为你用的是json解析哇,只能解析json格式的。
    使用x-www-form-urlencoded方式是编码了的,json解析不了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录

    报告相同问题?

    问题事件

    • 已结题 (查看结题原因) 8月21日
    • 已采纳回答 8月21日
    • 修改了问题 8月21日
    • 修改了问题 8月21日
    • 展开全部

    悬赏问题

    • ¥30 c++类和数组实验代码
    • ¥20 C语言字符串不区分大小写字典排序相关问题
    • ¥15 关于#python#的问题:我希望通过逆向技术爬取1688搜索页下滑加载的数据
    • ¥15 关于Linux的终端里,模拟实现一个带口令保护的屏保程序遇到的输入输出的问题!(语言-c语言)
    • ¥15 学习C++过程中遇到的问题
    • ¥15 请问,这个嵌入式Linux系统怎么分析,crc检验区域在哪
    • ¥15 二分类改为多分类问题
    • ¥15 Unity微信小游戏上调用ReadPixels()方法报错
    • ¥15 如何通过求后验分布求得样本中属于两种物种其中一种的概率?
    • ¥15 q从常量变成sin函数,怎么改写python代码?