Formdata对象即使在调用append后也显示为空
问题描述:
在formdata中追加对象显示为空。Formdata对象即使在调用append后也显示为空
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
var formy = new FormData();
formy.append("file", $("#file")[0].files[0]);
console.log(formy);
});
});
</script>
</head>
<body>
<input id="file" type="file" size="40"><br><br>
<button>Send an HTTP POST request to a page and get the result back</button>
</body>
</html>
在控制台日志上面的代码的输出给了我
Formdata{}
append:function append()
arguments:null
caller:null
length:2
name:"append"
而console.log($("#file")[0].files[0])
给我文件{name: "document.pdf", lastModified: 1462959300000, lastModifiedDate: Wed May 11 2016 15:05:00 GMT+0530 (IST), webkitRelativePath: "", size: 5275…}
为什么追加为FORMDATA不工作?
答
我觉得DOM文件属性在追加时出错,从而无法识别DOM中导致调用者的文件属性为空异常。 而且FormData()必须返回一个选择器,它被初始化。 试试这个
<!DOCTYPE html>
<html>
<head>
<script src="scripts/jquery-2.2.1.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
//var formy = new FormData();
//formy must return valid DOM selector and since our FormData code is unknown,I am using Div as example
//formy.append($('input[type="file"]'), $("#file")[0].files[0]);
$('#div1').append($('input[type="file"]'), $("#file1")[0].files[0])
//Now no null encountered
// console.log($('div').append($('input[type="file"]'), $("#file1")[0].files[0]));
});
});
</script>
</head>
<body>
<input id="file1" type="file" size="40"><br><br>
<button>Send an HTTP POST request to a page and get the result back</button>
<div id="div1"></div>
</body>
</html>
因为:文件是一个jQuery扩展和不CSS规范的一部分,使用查询:文件不能采取由本机DOM querySelectorAll()方法提供的性能提升的优势。为了在现代浏览器中获得更好的性能,请改用[type =“file”]。 SRC:jQuery Api文档
答
实际上追加IS工作。但是你不能以这种方式记录。 要查看的内容,试试这个:
<script>
$(document).ready(function(){
$("button").click(function(){
var formy = new FormData();
formy.append("file", $("#file")[0].files[0]);
for(var pair of formy.entries()) {
console.log(pair[0]+', '+pair[1]);
}
});
});
</script>
我已经添加了相同的代码截图3个控制台声明。 首先是你的文件[0]对象。 其次是你的配对[0] +','+对1。 第三是你的表单对象,它会在你报告时为空。
为什么以及如何发生这种情况可以在这里阅读。这里没有重复理论的观点。
https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries
这也不能正常工作。我仍然得到Formdata {} –
@KanikaMidha让我知道你是否还有问题。 :) –