欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

前端根據(jù)后端返回的文本流逐個展示文本內(nèi)容代碼示例

 更新時間:2025年01月23日 08:47:39   作者:晨光熹微fd  
前端如何根據(jù)后端返回的文本流逐個展示文本內(nèi)容的實現(xiàn)步驟,前端調(diào)用特定方法來獲取文本流,然后通過處理這些文本流,逐個在界面上展示文本內(nèi)容,需要的朋友可以參考下

前端根據(jù)后端返回的文本流逐個展示文本內(nèi)容

1、前端調(diào)用方法

async function fetchStream(url, data, onSuccess, close, error) {
  const response = await fetch(url, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
  });

  if (!response.ok) {
    onSuccess(`服務(wù)響應(yīng)失敗,請稍后重試`);
    close();
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let result = '';
  while (true) {
    const { done, value } = await reader.read();
    if (done) {
      break;
    }
    const decodedValue = decoder.decode(value, { stream: true });
    result += decodedValue;
    onSuccess && onSuccess(decodedValue); // 每次接收到數(shù)據(jù)時,調(diào)用onSuccess
  }
  close();
  return result;
}

2、使用

const onSend = () => {
  if (!questionText.value.trim()) {
    message('不能發(fā)送空消息', { type: 'warning' });
    return;
  }
  chatList.value.push({
    index: chatIndex.value + 1,
    type: 'user',
    content: questionView.value
  });
  chatList.value.push({
    index: chatIndex.value + 1,
    type: 'assistant',
    content: ''
  });
  const data = {
    question: questionView.value,
    modelId: props.modelId,
    sessionId: sessionId.value
  };
  let streamContent = '';
  const onStreamSuccess = (chunk) => {
    streamContent += chunk;
    chatList.value[chatList.value.length - 1].content = streamContent.replace(/\n+/g, ' ').replace(/ {2,}/g, ' ');
    scrollToBottom();
  };
  fetchStream(
    '/ai/aiAgent/stream',
    data,
    onStreamSuccess,
    () => {
      sendloading.value = false;
    },
    () => {
      chatList.value[chatList.value.length - 1].content = '';
      sendloading.value = false;
    }
  );
};

經(jīng)過以上兩步,即可實現(xiàn)文本流逐個顯示在界面上。

總結(jié)

到此這篇關(guān)于前端根據(jù)后端返回的文本流逐個展示文本內(nèi)容的文章就介紹到這了,更多相關(guān)根據(jù)后端文本流展示文本內(nèi)容內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論