javascript - 如何在 PHP 中 ajax 成功后重置图像文件预览?
问题描述
我正在使用 ajax 和 PHP PDO 插入数据库。我有两个领域。1.消息和2.图像。我有一个问题,图像预览(浏览文件)在插入和显示数据后没有重置(在 ajax 成功后)。ajax 成功后,消息 Textarea 值正在重置,但不是图像预览。
阿贾克斯代码:
$(document).on("click", "#save", function (e) {
e.preventDefault();
var message = $("#message").val();
var form_data = new FormData();
form_data.append('message', message)
var property = document.getElementById('photo').files;
property = property[0];
if (property) {
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
form_data.append("file", property);
}
$.ajax({
type: "POST",
url: "insert_posts.php",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function (data) {
//Insert data before the message wrap div
$(data).insertBefore(".message-wrap:first");
//Clear the textarea message
$("#message").val("");
$("#form")[0].reset();
$('#preview').attr('src', "#");
$("#photo").val("");
}
});
});
我正在使用 JS 在更改时预览图像(浏览图像并查看预览)
<script type="text/javascript">
//Image Preview Function
$("#uploadTrigger").click(function(){
$("#photo").click();
});
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#body-bottom').show();
$('#preview').attr('src', e.target.result);
$("#photo").val("");
}
reader.readAsDataURL(input.files[0]);
}
}
</script>
插入后消息值正在重置,但不是图像。我正在使用 HTML 代码行进行预览。
<div id="body-bottom">
<img src="#" id="preview"/>
</div>
应该重置图像预览并且 type="file" 我正在使用类型文件代码:
<input type="file" onchange="readURL(this);" style="display:none;" name="photo" id="photo">
<img src="assets/icon/icon1.png"></img><a href="#" id="uploadTrigger" name="post_image">Add Photo</a>
图像预览未重置。如果我再次单击相同的图像插入。我想在ajax成功后重置图像。
解决方案
我已经解决了这个问题。只需在表单重置上方添加行
$("#photo").val(""); $("#form")[0].reset();
或者您可以在最后放置表单重置。如果要隐藏预览,请添加行 -
$('#body-bottom').hide();
推荐阅读
- oracle11g - Oracle 错误:未声明存储过程参数值
- python - 如何在 Kivy、Python 中更新标签的文本
- google-maps - 比较 Google Maps V3 中的纬度/经度值
- php - PHP - 使用十六进制字符串解压模块
- node.js - 如何在浏览器中显示本地日期/时间?
- mysql - 我的“mySQL”代码有什么问题?存储过程?
- php - 使用 DomElement 为 AMP html 设置 [class] 属性
- java - Spring MVC中如何使用getById方法获取对应的名字?
- javascript - Web 组件:Dom 异常:此名称已被使用
- python - 如何使用户名和年龄的前3个字符他的名字然后年龄?