h5的fetch方法_HTML5 fetch API

介绍

fetch是传统XMLHttpRequest(也就是常说的ajax)的替代者,相比后者,它更简单,并且内置对Promise的支持。

但其实话说回来,我至今没太搞明白它的更多优点,因为说它使用简单好像体现不出优势,因为我们平时都是使用ajax框架的(比如jQuery),很少会直接使用原生XMLHttpRequest,而且用了它的话还要担心兼容性的问题。

语法

语法很简单:fetch(url, config),返回一个Promise对象。

基本使用

请求某个网页:

fetch('http://localhost/index.html')

.then(response => response.text())

.then(data => console.log(data));

请求某个JSON接口:

fetch('http://localhost/test.json')

.then(response => response.json())

.then(data => console.log(data));

请求某个图片:

fetch('http://localhost/test.jpg').then(response => response.blob())

.then(data =>

{

var img = new Image();

img.src = URL.createObjectURL(data); // 这个data是blob对象

document.body.appendChild(img);

});

Post请求fetch('https://blog.haoji.me/xxx.json', {

method: 'POST',

headers: {

'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'

},

body: 'a=1&b=2',

}).then(resp => resp.json()).then(resp => {

console.log(resp)

});

携带cookie

fetch默认是不携带cookie的,需要手动添加一个配置参数credentials: 'include':

fetch('http://localhost/test.json', {credentials: 'include'})

.then(response => response.json())

.then(data => console.log(data));

更多用法

自定义headervar headers = new Headers(

{

"Content-Type": "text/plain",

"X-Custom-Header": "aaabbbccc",

});

var formData = new FormData();

formData.append('name', 'lxa');

formData.append('file', someFile);

var config =

{

credentials: 'include', // 支持cookie

headers: headers, // 自定义头部

method: 'POST', // post方式请求

body: formData // post请求携带的内容

};

fetch('http://localhost/test.json', config)

.then(response => response.json())

.then(data => console.log(data));

当然,headers也可以这么初始化:

var content = "Hello World";

var myHeaders = new Headers();

myHeaders.append("Content-Type", "text/plain");

myHeaders.append("Content-Length", content.length.toString());

myHeaders.append("X-Custom-Header", "ProcessThisImmediately");

兼容性

兼容性目前不太好,Chrome42+和Firefox39+支持,IE全系列不支持。

参考

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在原生的 H5 中实现录音和录视频,可以使用 MediaStream API 和 getUserMedia() 方法。这些 API 可以访问设备上的摄像头和麦克风,并将捕获的媒体流转换为可用于录制或播放的数据。 下面是一个简单的示例,演示如何使用 H5 实现录音并将其上传: ```html <!DOCTYPE html> <html> <head> <title>录音上传示例</title> </head> <body> <button id="record">开始录音</button> <button id="stop">停止录音</button> <button id="upload">上传录音</button> <audio id="audio" controls></audio> <script> let mediaRecorder; let chunks = []; const constraints = { audio: true }; const recordBtn = document.getElementById('record'); const stopBtn = document.getElementById('stop'); const uploadBtn = document.getElementById('upload'); const audio = document.getElementById('audio'); recordBtn.addEventListener('click', async () => { try { const stream = await navigator.mediaDevices.getUserMedia(constraints); mediaRecorder = new MediaRecorder(stream); mediaRecorder.addEventListener('dataavailable', e => { chunks.push(e.data); }); mediaRecorder.addEventListener('stop', () => { const blob = new Blob(chunks, { type: 'audio/mp3' }); chunks = []; audio.src = URL.createObjectURL(blob); }); mediaRecorder.start(); } catch (error) { console.error(error); } }); stopBtn.addEventListener('click', () => { mediaRecorder.stop(); }); uploadBtn.addEventListener('click', () => { const blob = new Blob(chunks, { type: 'audio/mp3' }); const formData = new FormData(); formData.append('file', blob, 'recording.mp3'); fetch('/upload', { method: 'POST', body: formData }).then(response => { console.log('录音上传成功!'); }).catch(error => { console.error('录音上传失败:', error); }); }); </script> </body> </html> ``` 在这个示例中,我们创建了三个按钮:开始录音、停止录音和上传录音。当用户单击“开始录音”按钮时,我们使用 getUserMedia() 方法获取麦克风的访问权限,并创建一个 MediaRecorder 对象来录制音频。每当 MediaRecorder 对象接收到新的音频数据时,我们将其存储在一个数组中。当用户单击“停止录音”按钮时,我们停止录制,并将存储的音频数据转换为 Blob 对象。最后,当用户单击“上传录音”按钮时,我们将 Blob 对象作为表单数据发送到服务器。 类似地,你可以用类似的方法来实现录制视频。只需要将 constraints 对象中的 audio 属性改为 video 即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值