php - 通过 Ajax 将表单数据传递到 PhP
问题描述
我有一个同时使用文本字段和上传字段的表单。
<form action="submit" method="post" enctype="multipart/form-data">
<input type="text" name="textfield">
<input type="file" name="file_upload">
<button type="submit">Submit</button>
</form>
如何通过 ajax 传递所有插入的数据并使用 PhP 中的数据?
我目前通过 ajax 尝试的是:
var fd = new FormData($('form'));
$.ajax({
url: ajaxurl,
type: 'POST',
processData: false,
contentType: false,
data: {
fd: fd,
action: 'devplus_submit_annex' // a php function
},
success: function(response) {
JSON.parse(response);
},
error: function(response) {
console.log('Error');
}
});
解决方案
FormData 构造函数将 HTMLFormElement 作为其参数,您传递了一个 jQuery 对象。
对于 jQuery.ajax,您将表单数据对象单独作为数据字段传递。
如果您需要在 from 之外添加数据,您可以使用 append() 方法。
var fd = new FormData($('form')[0]);
fd.append('action', 'devplus_submit_annex');
$.ajax({
url: ajaxurl,
type: 'POST',
processData: false,
contentType: false,
data: fd,
success: function(response) {
JSON.parse(response);
},
error: function(response) {
console.log('Error');
}
});
推荐阅读
- c++ - 如何为带有时钟的程序创建计时器?
- sharepoint-2013 - 在 SharePoint 中管理完整列表中的唯一值
- html - 如何停止文本以旋转正确的动画?
- c++ - Xbox 360 无线控制器无法通过控制台应用程序中的 C++/WinRT 和 Windows.Gaming.Input API 工作
- r - 基于分组数据结构中的分位数过滤
- go - go pprof中的`Duration: 30.18s, Total samples = 26.26s (87.00%)`是什么意思?
- rx-java2 - RxJava:链接两个平面图
- apache-spark - 使用 foreachRDD 和 paho 将 PySpark 结果发送到 MQTT 代理
- python - 5 种不同模型的低训练 (~64%) 和测试准确率 (~14%)
- android - 具有设置可见性的 Recyclerview