当我们使用微信小程序对接ai功能时一般都需要打字机效果,一般ai接口都是sse协议,但是微信小程序不支持,垃圾东西,阉割了h5标准功能。我们需要给微信小程序模拟支持下。代码如下:
类库如下:
class EventSource {
constructor(url, retryTime = 0) {
this.url = url;
this.retryTime = retryTime;
this.listeners = {};
this.requestTask = null
this.connect()
}
connect() {
this.requestTask = wx.request({
url: this.url,
enableChunked: true,
responseType: 'text',
method: 'GET',
timeout: 300e3,
success: res => {
this.emit('success', res)
if (this.retryTime > 0) {
setTimeout(() => {
this.connect()
}, this.retryTime)
}
},
fail: () => {
}
});
this.requestTask.onHeadersReceived(res => {
this.emit('open', res);
})
this.requestTask.onChunkReceived(res => this.handleChunk(res))
}
handleChunk(res) {
console.log('ok');
const arrayBuffer = res.data;
const uint8Array = new Uint8Array(arrayBuffer);
let data = uni.arrayBufferToBase64(uint8Array)
data = new Buffer(data, 'base64')
data = data.toString('utf8')
const lines = data.split("\n\n")
lines.forEach(line => {
if (!line.trim()) {
return
}
const [key, value] = line.trim().split(':');
if (key === 'data') {
const data = line.substring(5).trim();
try {
const json = JSON.parse(data);
this.emit('message', {
data: json
})
} catch (e) {
this.emit('error', 'Api.EventSource.ParseError:' + e)
}
} else {
this.emit('error', 'Api.EventSource.ParseFail:' + line)
}
})
}
addEventListener(event, callback) {
if (!this.listeners[event]) {
this.listeners[event] = []
}
this.listeners[event].push(callback)
}
emit(event, data) {
if (this.listeners[event]) {
this.listeners[event].forEach(callback => {
callback(data)
});
}
}
close() {
if (this.requestTask) {
this.requestTask.abort()
}
}
}
module.exports = EventSource;调用方式参考例子:
const es = new EventSource('http://api.20230611.cn/api/question/aiExplanation?id=' + item.id)
es.addEventListener('open', res => {
that.showAiExplanation = status;
});
es.addEventListener('message', (event) => {
console.log('message');
});虽然支持了微信小程序,但是uniapp是基于webview实现,webview中不支持EventSource,太折腾了所以放弃了sse作为多平台协议的支持,还是websocket支持比较多。
window.setInterval(method,time)方法本身会返回一个资源句柄,使用clearInterval(Intervalid)方法即可清除定时器<script> var num=0; //每隔1秒再控制台输...
https://3gimg.qq.com/lightmap/v1/marker/index.html?marker=coord:37.6767600000,112.7297800000&key=TKUBZ-D24AF-GJ4JY-JDVM2-IBYKK-KEBCU&referer=p...
<!-- 三个核心方法 openDatabase:这个方法使用现有数据库或创建...
<!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script type...
HTML5 服务器发送事件(server-sent event)允许网页获得来自服务器的更新。通过官网的介绍可以看出是接收服务器发送数据,千万不能和ajax混淆,网上大片博文的介绍对其解读是错误的,导致让我差点觉得这个事件很鸡肋。先看通用案例:html5:<script type=&...
和腾讯合作的项目活动中腾讯要求我们必须隐藏朋友圈分享功能,一直以为没有官方Api,百般查找才在文档中找到,可能是自己不太细心。微信官方文档在jsjdk的"界面操作"中有详细说明:关闭当前网页窗口接口wx.closeWindow();批量隐藏功能按钮接口wx.hideMenuIte...