使用ajax调用从php服务器发送图像

Send image from php server using ajax call

本文关键字:图像 服务器 php ajax 调用 使用      更新时间:2023-09-26

我要做的就是搜索文件并显示来自服务器的图片。HTML有一个简单的搜索栏,允许您输入搜索词。JavaScript使用ajax请求调用PHP文件,PHP在服务器上找到图像并将其发送回显示。

现在发生的是图像没有显示,我得到一个图标,表示一些无效的图像。ajax调用似乎正在工作,但我认为我发回的数据是不正确的。我一直在试着搜索它,但是每个人似乎对如何做都有不同的看法,这有点令人困惑。

HTML

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">    </script>
<script src="search.js"></script>
<style type="text/css"></style>
</head>
</body>
    <header>
    <h1>My Page</h1>
    </header>
    <input type=text name="search" id="searchbox" placeholder="Search...">
    <input type=button value="Search" id=search><br>
    <div id="images"></div>
</body>
JavaScript

$(document).ready(function() {
    $("#search").on('click', function(){
        $.ajax({
           url: '/search.php',
           type: 'POST',
           data: $("#searchbox").serialize(),
           success: function(data) {
            $('#images').append(data);
           },
           error: function() {
            alert('failure');
           }
        });
    });
});
PHP

<?php
if(isset($_POST['search'])) {
    $searchterm = $_POST['search'];
    $image = "images/".$searchterm.".jpeg";
    echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';
}
else {
    echo 'Error: image not found';
}

p。目前,我忽略了任何类型的错误检查,我只是试图让它工作并假设输入都是有效的

建议:

  1. 试试这个链接:

使用PHP的图像数据uri

<?php
if(isset($_POST['search'])) {
    $searchterm = $_POST['search'];
    $image = "images/".$searchterm."jpeg";
    $imageData = base64_encode(file_get_contents($image));
    $src = 'data: '.mime_content_type($image).';base64,'.$imageData;
    echo '<img src="', $src, '">';
    ...
  • 调试jQuery/浏览器和PHP/后端服务器之间的实际HTTP流量。您可以使用Telerek Fiddler或Firebug等工具。
  • 希望这对你有帮助!

    使用file_get_contents,它将在浏览器上显示图像。

    $image = "images/".$searchterm.".jpeg";
    echo '<img src="data:image/jpeg;base64,'.base64_encode(file_get_contents($image)).'">';
    

    请更改对象中的url属性,在.ajax()方法调用中使用。您的search.php的路径不正确。

    $.ajax({
        url: '/search.php',
    

    →:

    $.ajax({
        url: './search.php',