首页 > 解决方案 > 如何使用 JQUERY/AJAX 显示包含图片和文本数据的多个数据,这些数据作为对象或数组发送?

问题描述

我找不到如何使用 JQUERY/AJAX 处理从服务器发送并包含二进制图片和文本数据的对象或数组的解决方案

好的,这是服务器端:

const url= require('url'),
      express = require('express'),
      fs = require ('fs'),
      app = express();
// Create a server

app.listen(8080, function (){
    console.log('Server running at http://127.0.0.1:8080/');
});

app.use (express.static (__dirname +'/public')); // provide public data,here: jQuery


app.get ("/", function (req, res){
    res.sendFile (__dirname +"/ClientServerExchange (2.5).html");
    console.log (__dirname +req.url);
});

app.get ("/image", function (req, res) {
    message = req.query.message;
    console.log (message);
    fs.readFile (message,  
    (err, myImg) => {
        var myData = {myImage: myImg, myText: "this a nice pic"};
//      var myData = [myImg, "this a nice pic"]; // if to be sent as array ...
        return res.send (myData);
    });

})

客户端:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes" >
        <title>Client-Server Exchange</title>
        <script src="JS/jquery-3.5.0.js"></script>
        <style>

        </style>
        <script type='text/javascript'>

            $(document).ready (function (){

                const message = encodeURI("../Workbench/Pics/myPic.jpg");

                $.ajax({
                    url: "/image?message=" +message,
                    dataType: 'json',
                    xhr: function(){// Seems like the only way to get access to the xhr object
                        var xhr = new XMLHttpRequest();
                        xhr.ResponseType = 'blob';
                        return xhr;
                    },
                    success: function(data){
                        console.log ("Request sent");
                        var blobData = new Blob ([data.myImage]);
                        src = URL.createObjectURL(blobData);
                        $("img").attr ("src", src); 
                        $("#addComment").text (data.myText);
                    },
                    timeout: 10000
                });
            });
        </script>
    </head>
    <body>
        <p>show a picture from my little server </p>
        <img src ="">
        <p id="addComment"></p>
    </body>
</html>

请求已发送,我假设来自服务器的响应包含所有数据。我可以从两个控制台中的消息中看到它。但是没有显示图片,只有一个小符号,看起来像一张破碎的图片。请求的文本出现在此符号之后。客户端和服务器端没有错误消息。

接收图片数据的唯一方式如$.ajax函数内部的xhr结构所示。我在 stackoverflow 平台上找到了解决方案。客户端脚本运行良好,如果我只发送图片数据(当然对客户端和服务器脚本稍作修改,但这不是这里的问题)。

我如何对客户端脚本进行编程,使其接收这样的对象并将myImage-part 视为 blob 并将myText-part 视为文本?

在此先感谢您的帮助。

标签: javascriptjqueryajaxexpress

解决方案


按照 Babak 的使用技巧,express.Router()我稍微修改了请求中的程序。

添加到服务器程序

const router = express.Router ();

app.use ("/image", router);

在那里app.get ("/image", function (req, res) { ...});替换

router.get ("/", function (req, res) {
    message = req.query.message;
    console.log (message);
    fs.readFile (message,  
    (err, myImage) => {
        return res.send (myImage);
    }); 
});

并添加

router.get ("/Title", function (req, res) {
    res.send ("This is a nice pic!");
})

在客户端替换$.ajax({ ... });

                $.ajax({
                    url: "/image?message=" +message,
                    xhr: function(){// Seems like the only way to get access to the xhr object
                        var xhr = new XMLHttpRequest();
                        xhr.responseType = 'blob';
                        return xhr;
                    },
                    success: function(data){
                        console.log ("Request sent");
//                      var blobData = new Blob([data]); // not necessary
//                      var url = window.URL || window.webkitURL;
                        src = URL.createObjectURL(data); // could be blobData, if defined, but works also without this.
                        $("img").attr ("src", src);                 
                    }
                });

并在下面添加$(document).ready (function (){ ... })

                $.get ("/image/Title", function (data) {
                    $("#addComment").text (data);
                })

显然不可能在对象或数组中发送二进制数据(我不确定,因为我认为已经读过这个,但我不知道在哪里......)。无论如何,上述解决方案有效。


推荐阅读