简体   繁体   English

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

[英]How can I show multiple data containing picture and text data with JQUERY/AJAX, which are sent as object or array?

I can't find a solution how to handle an object or an array sent from a server and containing binary picture and text data with JQUERY/AJAX我找不到如何使用 JQUERY/AJAX 处理从服务器发送并包含二进制图片和文本数据的对象或数组的解决方案

Ok, here is the server side:好的,这里是服务器端:

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);
    });

})

The client side:客户端:

<!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>

The request is sent and I assume the response from the server contains all data.请求被发送,我假设来自服务器的响应包含所有数据。 I can see it from the messages in both consoles.我可以从两个控制台的消息中看到它。 But no picture is shown, only a small symbol instead, which looks like a broken picture.但是没有显示图片,只有一个小符号,看起来像一张破碎的图片。 The requested text appears after this symbol.请求的文本出现在此符号之后。 There is no error message on client and server side.客户端和服务器端没有错误消息。

The only way to receive picture data is as shown in the xhr structure inside the $.ajax function.接收图片数据的唯一方法如$.ajax函数内的xhr 结构所示。 I found the solution here at the stackoverflow platform.我在 stackoverflow 平台上找到了解决方案。 Client script works well, if I send picture data only (of course with slight modifications of the client and server script, but this is not the question here).客户端脚本运行良好,如果我只发送图片数据(当然对客户端和服务器脚本稍作修改,但这不是这里的问题)。

How can I program the client script, that it receives such an object and shall treat the myImage -part as a blob and the myText -part as a text?我如何编写客户端脚本,让它接收这样一个对象,并将myImage -part 视为 blob,将myText -part 视为文本?

Thanks in advance for your help.在此先感谢您的帮助。

Following to Babak's tip of using express.Router() I modified the program in my request a little bit.根据 Babak 使用express.Router()的提示,我在我的请求中稍微修改了程序。

Add to server program添加到服务器程序

const router = express.Router ();

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

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

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

and add并添加

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

On client side replace $.ajax({ ... });在客户端替换$.ajax({ ... }); with

                $.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);                 
                    }
                });

and add below this inside $(document).ready (function (){ ... })并在$(document).ready (function (){ ... })

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

Obviously it is not possible to send binary data inside an object or array (I'm not sure, because I think to have read this, but I don't know where ...).显然,不可能在对象或数组中发送二进制数据(我不确定,因为我认为已经阅读了这个,但我不知道在哪里......)。 Anyway, the solution above works.无论如何,上述解决方案有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将多个数据从PHP传递到jQuery / AJAX? - How can I pass multiple data from PHP to jQuery/AJAX? 如何使jQuery(javascript)ajax表单数据发送的可读性降低? - How can i make jQuery(javascript) ajax form data sent less human readable? 我在ajax成功中收到我的数据如何在表中显示jquery数据 - I am receiving my data in ajax success how can I show jquery data in table jquery-无法从我通过 ajax 调用得到的 object 类型响应中检索数据 - jquery- can not retrieve data from object type response which I get through ajax call 如何通过Ajax在多个URL中发送数据 - How to sent data by ajax in multiple urls 如何使用 JQUERY 从 JSON 数组对象获取数据? - How can I get data from JSON array object with JQUERY? 我如何使用JS和AJAX发送数组 - How can i sent an array with JS and AJAX 我如何获取 get api 调用的数据,格式为 reactjs 中 object 数组中的 object 嵌套数组? - How can i fetch the data of an get api call which is in the format as nested array of object in array of object in reactjs? 可以使用jquery .ajax()调用解析包含xml数据的javascript对象吗? - Can a javascript object containing xml data be parsed using the jquery .ajax() call? 如何显示多个同步jQuery Ajax调用的进度? - How can I show progress of multiple synchronous jQuery Ajax calls?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM