jquery - 如何从模态窗口传递 id 值以单击 ajax 事件?
问题描述
我有一张带有照片的表格,当我单击图像时,会打开一个模式窗口,我想在其中更新图像。为了检查图像的 id 是否正确,我创建了一个警告窗口,并在此窗口中显示了正确的 id。我想使用 ajax 方法更新图像,但我无法将 id 传递给 ajax,我创建了一个警告窗口来查看它并抛出 -> 未定义。如何将 id 传递给 ajax 以进一步使用它?
$(document).ready(function() {
var wrap = $('#wrapper'),
modal = $('.overlay, .modal, .content_modal');
$('.open_modal_btn').click(function(event) { //open modal window
modal.fadeIn();
alert( $(this).attr('data-id')); //shows the correct id
var id = $(this).data('id'); //assign id to a variable
$("#ajax_update").on('submit',(function(e) { //pressing save button after selecting an image from a folder
e.preventDefault();
alert(id); // here no longer shows id, shows undefined
var fd = new FormData();
var files = $('#file').files;
fd.append('file',files);
fd.append('request',1);
fd.append('id', id);
$.ajax({
url: "./update_photo.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData:false,
success: function(data){
if(data=='invalid'){
// invalid file format
console.log(data);
}else{
// view uploaded file
$("#photo").attr('src',"../api/img/"+data).fadeIn();
$("#ajax_update").reset();
console.log(data);
}
},
error: function(e){
console.log(data);
}
});
}));
});
$('.modal').click(function() { // close modal window
wrap.on('click', function(event) {
var select = $('.content_modal');
if ($(event.target).closest(select).length)
return;
modal.fadeOut();
wrap.unbind('click');
});
});
});
文件 php
if($request == 1){
$id= $_POST['id']; //id from ajax request
解决方案
你不应该使用$(this).attr('data-id')
和$(this).data('id')
互换。
FormData.append
将 File 对象作为第二个参数,而不是 FileList。
您可以通过 data 参数将按钮 id 传递给回调函数。
$('.open_modal_btn').click(function(event) { //open modal window
modal.fadeIn();
$("#ajax_update").on('submit', {id: $(this).attr('data-id')}, (function(e) { //pressing save button after selecting an image from a folder
e.preventDefault();
alert(e.data.id); // here no longer shows id, shows undefined
var fd = new FormData();
var file = $('#file').files[0]; //assuming you're uploading 1 file
fd.append('file',file);
fd.append('request',1);
fd.append('id', e.data.id);
$.ajax({
url: "./update_photo.php",
type: "POST",
data: fd,
contentType: false,
cache: false,
processData:false,
success: function(data){
if(data=='invalid'){
// invalid file format
console.log(data);
}else{
// view uploaded file
$("#photo").attr('src',"../api/img/"+data).fadeIn();
$("#ajax_update").reset();
console.log(data);
}
},
error: function(e){
console.log(data);
}
});
}));
});
推荐阅读
- c# - 运行 api 的自动化测试时出现错误的请求错误
- java - 使用 Spring Kafka 自定义转换 Apache Kafka 标头
- android - 使用 YouTube 作为托管平台来嵌入具有下载功能的视频?
- python - 将 Linkedin 学习视频源导出为 .txt 文件
- adsense - 在我的公开直播网站上设置 Google Adsense
- youtube-api - 每 100 秒的 youtube 配额限制
- javascript - 如何将样式属性删除到段落内的其他标签并仅保留一个样式
- spring-boot - Springboot 验证在 Kotlin 中不起作用
- python - 如何在 python 中从一组具有序列化命名的变量创建列表
- python - 在任何地方运行 python 脚本