赞
踩
前端jquery代码:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Streaming Response Example</title>
- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
- </head>
- <body>
- <textarea id="output" rows="10" cols="50"></textarea>
- <input type="number" id="quantity" min="1" placeholder="Enter quantity">
- <button id="submit">Submit</button>
-
- <script>
- $(document).ready(function() {
- var output = $('#output');
- var quantityInput = $('#quantity');
- var submitButton = $('#submit');
-
- submitButton.on('click', function() {
- var quantity = parseInt(quantityInput.val());
-
- if (isNaN(quantity) || quantity <= 0) {
- alert("Please enter a valid quantity.");
- return;
- }
-
- fetch('/stream_data?quantity=' + quantity)
- .then(response => {
- const reader = response.body.getReader();
- return new ReadableStream({
- start(controller) {
- function push() {
- reader.read().then(({ done, value }) => {
- if (done) {
- controller.close();
- return;
- }
- controller.enqueue(value);
- push();
- });
- }
- push();
- }
- });
- })
- .then(stream => {
- const decoder = new TextDecoder();
- const reader = stream.getReader();
-
- function processText({ done, value }) {
- if (done) return;
- const text = decoder.decode(value, { stream: true });
- console.log("received data -", text);
- output.val(output.val() + text);
- reader.read().then(processText);
- }
-
- reader.read().then(processText);
- })
- .catch(error => {
- console.error('Error:', error);
- });
- });
- });
- </script>
- </body>
- </html>
jquery2示例:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Streaming Response Example</title>
- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
- </head>
- <body>
- <div id="app">
- <textarea id="output" rows="10" cols="50"></textarea>
- <input type="number" id="quantity" min="1" placeholder="Enter quantity">
- <button id="submit">Submit</button>
- </div>
-
- <script>
- $(document).ready(function(){
- $('#submit').click(function(){
- var output = $('#output');
- var quantity = $('#quantity').val();
- fetch(`/stream_data?quantity=${quantity}`, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- }
- })
- .then(response => {
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
-
- reader.read().then(function processText({ done, value }) {
- if (done) {
- //output.val('');
- return;
- }
- const text = decoder.decode(value, { stream: true }).replace('undefined', '');
- console.log("received data -", text);
-
- output.val(output.val() + text);
- reader.read().then(processText);
- });
- })
- .catch(error => {
- console.error('Error:', error);
- });
- });
- });
- </script>
- </body>
- </html>
vue代码示例:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Streaming Response Example</title>
- <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js"></script>
- </head>
- <body>
- <div id="app">
- <textarea id="output" rows="10" cols="50">{{ outputText }}</textarea>
- <input type="number" id="quantity" min="1" v-model.number="quantity" placeholder="Enter quantity">
- <button @click="submit">Submit</button>
- </div>
-
- <script>
- new Vue({
- el: '#app',
- data: {
- outputText: '',
- quantity: 1
- },
- methods: {
- async submit() {
- try {
- const response = await fetch(`/stream_data?quantity=${this.quantity}`, {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- }
- });
-
- if (!response.body) return;
-
- const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
- while (true) {
- const { value, done } = await reader.read();
- if (done) break;
- const text = value?.replace('undefined', '');
- console.log("received data -", text);
- this.outputText += text;
- }
- } catch (error) {
- console.error('Error:', error);
- }
- }
- }
- });
- </script>
- </body>
- </html>
后端python接口:
- from flask import Flask, Response, send_from_directory, request
- import time
-
- app = Flask(__name__, static_folder='static')
-
- # @app.route('/')
- # def index():
- # return app.send_static_file('index.html')
-
- @app.route('/<html_file>')
- def serve_html(html_file):
- return send_from_directory(app.static_folder, html_file)
-
-
-
- @app.route('/stream_data')
- def stream_data():
- quantity = int(request.args.get('quantity', 10)) # 获取数量值,默认为10
- if quantity <= 0:
- return "Invalid quantity value", 400 # 返回400错误
-
- def generate():
- for i in range(quantity):
- yield f"Data point {i}\n"
- time.sleep(1) # 模拟生成数据的延迟
-
- return Response(generate(), mimetype="text/event-stream")
-
- if __name__ == '__main__':
- app.run(host='0.0.0.0', port=8666)
-
其他。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。