js方法--fetch

fetch()方法与XMLHttpRequest类似,fetch也可以发起ajax请求,但是与XMLHttpRequest不同的是,fetch方式使用Promise,相比较XMLHttpRequest更加的简洁。fetch是全局量window的一个方法.

fetch方法的then会接收一个Response实例,值得注意的是fetch方法的第二个then接收的才是后台传过来的真正的数据,一般第一个then对数据进行处理等。例如fetch处理JSON响应时 回调函数有一个json()方法,可以将原始数据转换为json对象

基本使用:

fetch('test.json', {   //url (必须), options (可选)
     method:'POST'
    })
	.then(function(res){
		return res.json();
	})
	.then(function(data){
		console.log(data)
    //{name: "test", sex: "nan"}
	})

url参数是必须要填写的,option可选,设置fetch调用时的Request对象,如method、headers等
比较常用的Request对象有:

  • method(String): HTTP请求方法,默认为GET
  • body(String): HTTP的请求参数
  • headers(Object): HTTP的请求头,默认为{}
  • credentials(String): 默认为omit,忽略的意思,也就是不带cookie;还有两个参数,same-origin,意思就是同源请求带cookie;include,表示无论跨域还是同源请求都会带cookie

GET请求:

fetch('test.js?id=12') //get方式可直接在url后面传参
	.then(function(response){
		console.log(response)
		return response.json();

	})
	.then(function(data){
		console.log(data)
	})

POST请求:


fetch('/api/getItems', {
    body: JSON.stringify(params), //json字符串和对象都可以,推荐使用json字符串,这样可以在控制台network里看到请求参数
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'include', // include, same-origin, *omit
    headers: {
      'Content-Type': 'application/json'
    },
    method: 'POST'
  }).then(response => response.json()).then(res => {
      console.log(res)
  })

具体参考:https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值