我有一个想要将其数据发送到admin-ajax
的表格:
<form method="POST" id="form">
<input type="text" name="name">
<input type="number" name="phone">
<input type="email" name="email">
<textarea name="overview"></textarea>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
使用Ajax发送数据的Javascript / jQuery代码:
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var form_data = $('#form').serialize();
$.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: form_data + {action: 'my_action'},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
还尝试了formData
:
var form_data = new FormData();
form_data.append('form', $('#custom').serialize());
form_data.append('action', 'my_action');
如何发送表单数据和操作my_action
?
答案 0 :(得分:1)
您需要将此行从data: form_data + {action: 'my_action'},
更改为data: {action: 'my_action', form_data:form_data},
jQuery(document).on("click","#submit", function(){
e.preventDefault();
var form_data =jQuery('#form').serializeArray();
jQuery.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: {action: 'my_action', form_data:form_data},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
并将输入类型submit
更改为button
。
答案 1 :(得分:0)
通常,我更喜欢使用这种方式,就像您使用的是“提交类型”按钮一样:
$(document).on('click', '#submit', function(){ // the id of your submit button
var form_data = $('#your_form_data_id'); // here is the id of your form
form_data.submit(function (e) {
var my_action = "my_action";
e.preventDefault();
$.ajax({
type: form_data.attr('method'), // use this if you have declared the method in the form like: method="POST"
url: form_data.attr('action'), // here you have declared the url in the form and no need to use it again or you can also use the path like in your code
data: form_data.serialize() +'&'+$.param({ 'my_action': my_action}), // here you are sending all data serialized from the form and appending the action value you assing when declare var my_action
success: function (data) {
// after the success result do your other stuff like show in console, print something or else
},
});
});
});
希望它对您有帮助。如果不清楚,请随时在评论中解释。
答案 2 :(得分:0)
您应该只将表单传递给新的FormData(),因此在您提交表单时,只需传递新的FormData(e.target);
希望有帮助