从Rest API获取图像.JQuery的问题

Getting image from Rest API. JQuery issues

本文关键字:JQuery 问题 图像 获取 Rest API      更新时间:2023-09-26

两个相关的问题。

(this is my jquery.js file)
$.ajax
    ({
     type: "GET",
     url: "url",
     dataType: 'image/png',
     async: false,
     beforeSend: function (xhr) {
     xhr.withCredentials = true;
     xhr.setRequestHeader("Authorization", "Bearer xxxx");
     },
     success: function (data) {
     document.getElementById("myImage").src = data; // (will be in next question)
     console.log(data);
     }
     });

当我得到JSON数据时,它会通过console.log将该数据放入chrome控制台(开发人员工具)。然而,对于png,我没有看到任何数据。这让我很担心,因为在图片的请求响应中,我看到二进制数据

�Ս-��tKn�v���6�k�˟>��������7�&=���+���?J�k�����y����L���m�(ψ/

但我需要确保这是在数据变量中,因为。src = data行。

这引出了我的下一个问题....如果图像二进制数据是在"数据"变量,它不应该显示在我的html?

<html>
    <head>
        <script src="//code.jquery.com/jquery-2.0.0.min.js"></script>
        <script src="jquery.js"></script>
    </head>
    <body>
        <img id="myImage" src="" />
    </body>
</html>

谢谢!

为什么需要ajax调用呢?把

document.getElementById("myImage").src = url;

即使你通过ajax调用获得图像的内容,绕过所有浏览器问题,编码问题等,你也不能只是显示该图像,因为img的"src"属性接受URL而不是数据流。

除此之外,你的代码看起来很好,如果我去JQuery.com并在控制台中运行这个(FireFox -最新),我将得到数据流:

$.ajax
    ({
     type: "GET",
     url: "http://jquery.com/jquery-wp-content/themes/jquery.com/i/feature-sprites.png",
     dataType: 'image/png',
     async: false,
     success: function (data) {
        console.log(data);
     }
     });

你可能想确保你的身份验证没有失败,因为你可能在一个不同于API的域上运行脚本,你应该确保API允许CORS(跨域资源共享),这基本上意味着你可以从不同的域调用它。