fetch 函数传递参数与后台交互

版权声明:转载注明来源 https://blog.csdn.net/love_moon821/article/details/85680931

介绍fetch函数:fetch( input [,init ]).then(function(response){ })

input定义要获取的资源。这可能是:

  • 一个 USVString 字符串,包含要获取资源的 URL。一些浏览器会接受blob:和data: 作为 schemes.
  • 一个 Request 对象。

init 可选:

一个配置项对象,包括所有对请求的设置。可选的参数有:

  • method:请求使用的方法,如GET、POST
  • headers:请求的头信息,形式为 Headers的对象或包含 ByteString值的对象字面量。
  • body:请求的 body 信息:可能是一个 BlobBufferSourceFormDataURLSearchParams或者 USVString 对象。注意 GET 或 HEAD 方法的请求不能包含 body 信息。cors no-cors 或者 same-origin
  • mode:请求的模式,如cors 、no-cors 或者 same-origin。
  • credentials: 请求的 credentials,如 omit、same-origin或者include。为了在当前域名内自动发送cookie,必须提供这个选项。
  • cache:请求cache模式:default、no-store、reload、no-cache、fore-cache 或者 only-if-cached。
  • redirect: 可用的 redirect 模式: follow(自动重定向), error(如果产生重定向将自动终止并且抛出一个错误), 或者 manual(手动处理重定向). 在Chrome中,Chrome 47之前的默认值是 follow,从 Chrome 47开始是 manual。
  • referrer: 一个 USVString 可以是 no-referrer、client或一个 URL。默认是client
  • referrerPolicy: Specifies the value of the referer HTTP header. May be one of no-referrer no-referrer-when-downgrade、origin origin-when-cross-origin、UNsafe-url。
  • integrity: 包括请求的  subresource integrity 值 ( 例如: sha256-BpfBw7ivV8q2jLiT13fxDYAe2tJllusRSZ273h2nFSE=)。

返回值:一个 Promise,resolve 时回传 Response 对象。

示例:与后台交互并传递参数(这里只是说明,要访问,请自行更改)

前端:

fetch(‘www/getData’, {method:'POST'
                      ,headers:{ 'Content-Type': 'application/json' }
                      ,body: JSON.stringify({ key: value,key1:value1...... })
                   }).then( function (resp) {
                      console.log(resp);
                      return resp.blob() })

访问的路径:URL= 'www/getData'

请求的方法: POST

传递多个参数:JSON.stringify({ key: value,key1:value1...... })

后台:以java为例

@RequestMapping(value = "getData", method = RequestMethod.POST)
public Object getData(@RequestBody Map<String, Object> map){
	
}

可以从map.get("key") 对应的value值。。。。。。;

记得要用:@RequestBody 

@RequestParam 和 @PathVariable 不可以

想想就知道
 

猜你喜欢

转载自blog.csdn.net/love_moon821/article/details/85680931