jQueryAJAX-将数据POST到IMG标签


jQuery AJAX - POST data to IMG tag

file.php

<?php
  $variable = 'mainImage';
?>
<div>
  <img src="image.php">
</div>
<input type="button" onClick="">

我正在尝试执行以下操作:

单击按钮时,应将$variable传递给image.php,并相应地重新加载图像。是的,我知道我们可以将src更新为image.php?variable=mainImage。($_GET(

但是,是否可以通过$_POST发送$variable而不刷新页面,只刷新图像?

您可能可以使用数据URI来获得以下内容:

// Instead of simply storing the URL as the src attribute,
//   execute the post and shove the data into a data URL
$.post('image.php', {variable: 'value'}, function(data) {
    image.src = "data:image/jpeg;base64," + data;
});

ajaxTransport文档的最小图像传输部分中,可能还有一些关于如何更紧密地集成此类功能的有用信息。

当然,您可以使用jQuery来实现这一点。我建议在这样做之前给你的图像一个id,这样我们就可以选择特定的图像并获取来源,所以这样做吧。

<img id="main-image"  src="image.php">
$(function(){
   var main_image = $('#main-image'); 
   var url = main_image.attr('src'); 
   $.post( url, { variable: '<?php echo $mainImage ?>' }, function( data ){
      main_image.attr('src', data);  
   })
});