首页 > 解决方案 > 通过 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');
    }
});

标签: phpajaxforms

解决方案


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');
    }
});

推荐阅读