使用Fetch GET请求设置查询字符串 [英] Setting query string using Fetch GET request

查看:147
本文介绍了使用Fetch GET请求设置查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新的Fetch API: https:// developer .mozilla.org / zh / docs / Web / API / Fetch_API

I'm trying to use the new Fetch API: https://developer.mozilla.org/en/docs/Web/API/Fetch_API

我正在发出这样的GET请求:

I am making a GET request like this:

var request = new Request({
  url: 'http://myapi.com/orders',
  method: 'GET'
});
fetch(request);

但是,我不确定如何向GET请求添加查询字符串。理想情况下,我希望能够向以下URL发出GET请求:

However, I'm unsure how to add a query string to the GET request. Ideally I want to be able to make a GET request to a URL like:

'http://myapi.com/orders?order_id=1'

在jQuery中我可以通过传递 {order_id来做到这一点:1} 作为 $。ajax() data 参数。使用新的Fetch API是否有相同的方法?

In jQuery I could do this by passing {order_id: 1} as the data parameter of $.ajax(). Is there an equivalent way to do that with the new Fetch API?

推荐答案

2017年3月更新

URL.searchParams 支持已正式登陆Chrome 51,但其他浏览器仍需要 polyfill

URL.searchParams support has officially landed in Chrome 51, but other browsers still require a polyfill.

官方使用查询参数的方法就是添加它们到URL。从规范,这是一个例子:

The official way to work with query parameters is just to add them onto the URL. From the spec, this is an example:

var url = new URL("https://geo.example.org/api"),
    params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)

但是,我不确定Chrome是否支持 searchParams URL的属性(在撰写本文时),因此您可能希望使用第三方库自己动手解决方案

However, I'm not sure Chrome supports the searchParams property of a URL (at the time of writing) so you might want to either use a third party library or roll-your-own solution.

2018年4月更新:

使用 URLSearchParams构造函数您可以分配2D数组或对象t并将其分配给 url.search ,而不是循环所有键并附加它们

With the use of URLSearchParams constructor you could assign a 2D array or a object and just assign that to the url.search instead of looping over all keys and append them

var url = new URL('https://sl.se')

var params = {lat:35.696233, long:139.570431} // or:
var params = [['lat', '35.696233'], ['long', '139.570431']]

url.search = new URLSearchParams(params)

fetch(url)

旁注: URLSearchParams 也是在NodeJS中可用

Sidenote: URLSearchParams is also available in NodeJS

const { URL, URLSearchParams } = require('url');

这篇关于使用Fetch GET请求设置查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆