如何将其他数据发送到javascript的fetch()函数 [英] How do I sent additional data to javascript's fetch() function

查看:86
本文介绍了如何将其他数据发送到javascript的fetch()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用fetch()来查询为我的搜索页面提供动力的API端点.它以JSON格式返回搜索结果列表.

I want to use fetch() to query an API endpoint which powers my search page. It returns a list of search results in JSON format.

我还想将用户提交的当前查询传递给API.旧的实现使用jquery和 getJSON .查看getJSON文档,它说我可以传入data变量:

I also want to pass to the API the current query submitted by the user. The old implementation used jquery and getJSON. Looking at the docs for getJSON, it says that I can pass in a data variable:


data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.

查看文档,我不确定如何将数据作为请求的一部分传递.所以我的问题是,如何传递将与请求一起发送到服务器的字符串?

Looking at the docs for fetch, I'm not sure how to pass in data as part of my request. So my question is, how do I pass in a string that will be sent to the server along with my request?

我想我可以将查询附加到请求URL,例如"/search/?q = Something",然后发送该查询.有谁有更好的方法?

I think I can append the query to the request URL, like "/search/?q=Something" and send that. Does anyone have a better way?

推荐答案

如果您查看,其中列出了几种类型的值,可用于指定请求中发送的数据.

If you look at the Body section of the documentation on fetch, it lists several types of values you can use to specify the data sent in your request.

使用FormData的示例:

var fd = new FormData();
fd.append('q', 'Something');

fetch('/search', {
  method : "POST",
  body : fd
})
.then(...)

请注意,您不能在GET或HEAD请求上使用body选项(看来您可能正在这样做).在这种情况下,您可以使用URLSearchParams建立参数:

Note that you can't use the body option on GET or HEAD requests (which it seems you may be doing in your case). In that situation, you can build up the parameters using URLSearchParams:

var params = new URLSearchParams();
params.append('q', 'Something');

fetch('/search/?' + params.toString(), {
    method: 'GET'
})
.then(...);

这篇关于如何将其他数据发送到javascript的fetch()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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