[我正在尝试用jquery编写一个脚本,该脚本可以遍历所有输入字段并将其附加到formData对象。
我之前在'普通'JS中也做过同样的事情,而且效果很好-但我不明白为什么这不适用于jquery ...-它根本不向formData对象添加任何内容...
这是我的旧JS示例:
<input type="file" name="upload_file" onchange="post_form('target_url.asp');">
<script type="application/javascript">
function post_form(target_url) {
var inp = document.getElementsByTagName("input");
var i_a;
var fil_x;
var str_val = new FormData();
for (i_a = 0; i_a < inp.length; i_a++) {
if (inp[i_a].type == "file") {
for (fil_x = 0; fil_x < inp[i_a].files.length; fil_x++) {
str_val.append("file", inp[i_a].files[fil_x], inp[i_a].files[fil_x].name);
}
}
}
pgf = new XMLHttpRequest();
pgf.open("POST", target_url, true);
pgf.send(str_val);
}
</script>
这是我的新脚本,应该执行相同的操作,但是用jqeury代替...但是它不起作用-没有任何内容发送到服务器...我认为它实际上没有将其附加到formData ...
<input type="file" name="upload_file" onchange="post_form('target_url.asp');">
<script type="application/javascript">
function post_form(target_url) {
var r_data = new FormData();
$(document).find("input, select, textarea").each(function() {
if ($(this).attr("type") !== "checkbox" && $(this).attr("type") !== "radio") {
if ($(this).attr("name") != undefined) {
r_data.append($(this).attr("name"), $(this).val());
}
} else {
if ($(this).is(":checked")) {
if ($(this).attr("name") != undefined) {
r_data.append($(this).attr("name"), $(this).val());
}
}
}
});
$.ajax({
type: "POST",
url: target_url,
data: r_data,
processData: false,
cache: false,
contentType: false,
});
}
</script>
<script type="text/javascript" src="jquery.min.js"></script>
我用jquery搜索并尝试了很多不同的示例,但我看不出为什么这与众不同-以及为什么它不起作用...
谢谢
[.find()
适用于单个选择器,您完全不需要在这里使用它:
.find()