首页 > 解决方案 > XHR GET 请求参数对象

问题描述

因此,我试图弄清楚如何使用 GET 请求进行 XHR,该请求将像这样格式化参数:

https:://api.com/endpoint?id=userId&list=list1%5D=1&list=list2%5D=1

我正在构建一个名为列表的对象,看起来像

const lists = {
   'list1' : 1,
   'list2': :1
}

我知道这适用于 $.ajax,如下所示:

    $.ajax({
      url: 'https://api.com/endpoint',
      dataType: 'json',
      data: {
        "type": "POST",
        "id": userId,
        "lists": lists
      }
    })

但我需要用香草 JS 来做到这一点。我尝试了以下方法:

    const params = `type=POST&id=${userId}&lists=${lists}`
    const xhr = new XMLHttpRequest()

    xhr.open('GET', `https://api.com/endpoint${params}`);

    xhr.send(encodeURI(params))

那只是试图击中: https://api.com/endpoint&type=POST&id=userId&lists=[object%20Object]

所以我的主要工作是尝试获取 URL 以将列表参数格式化为 &list=list1%5D=1&list=list2%5D=1

我希望这是有道理的!

干杯

标签: javascriptxmlhttprequest

解决方案


推荐阅读