2016-03-07 121 views
0

我正在创建一个包含上传文件列表的表,并且我想在最后一列中添加一个链接以允许用户删除相应的文件。我可以简单地使用链接“delete.php?fileid =”,但我更喜欢使用POST请求,所以我决定使用一个表单,将数据库中文件的ID作为隐藏输入传递。 ()():.closest('form')。find(“:input”)。serialize());方法如下:返回一个空字符串。你能帮助理解什么是根本原因?

代码形式提交:

$('.f-delete a'). click(function(e){ 
     e.preventDefault(); 
     console.log($(this).closest('form').find(":input").serialize()); 
     $.ajax({ 
      type: "POST", 
      url: 'delete_image.php', 
      dataType: 'json', 
      data: $(this).closest('form').find(":input").serialize(), 
      success: function(response){ 
       console.log(response); 
      }, 
      error: function(){ 
       alert('Error: Could not delete the file'); 
      } 
     }); 
    }); 

的标记:

<table class="table table-striped"> 
    <thead> 
    <tr> 
     <th>Title</th> 
     <th>Type</th> 
     <th>Size</th> 
     <th></th> 
    </tr> 
    </thead> 
    <tbody> 
    <tr> 
     <td>Test file</td> 
     <td>image/png</td> 
     <td>302.65 KB</td> 
     <td> 
     <form id="f-1" class="f-delete" method="post" action="delete_image.php"> 
      <input id="id-1" value="1" type="hidden"> 
      <a id="a-1" href="">Delete image</a> 
     </form> 
     </td> 
    </tr> 
    <tr> 
     <td>Test file 2</td> 
     <td>image/png</td> 
     <td>37.88 KB</td> 
     <td> 
     <form id="f-2" class="f-delete" method="post" action="delete_image.php"> 
      <input id="id-2" value="2" type="hidden"> 
      <a id="a-2" href="">Delete image</a> 
     </form> 
     </td> 
    </tr>     
    </tbody> 
</table> 
+2

?你试试明显,控制台记录'$(本).closest( '形式')找到(”。 :输入“)。serialize()'看到你实际上有数据? – adeneo

+0

另外请注意,你期望JSON被返回,其他任何事情都会失败。 – adeneo

+0

请发送delete_image.php代码 –

回答

1

的问题是在你的HTML,使用serialize您输入的应该有名字。例如:

<input id="id-1" value="1" name="id-1" type="hidden"> 

对于顺序使用

$(this).closest('form').serialize() //return id-1=1 

结果https://jsfiddle.net/cmedina/1Lv8gkms/