更新时间:2023-12-04 23:16:40
以下是一些常规步骤。请注意,这些只是示例,而不是完整的代码。您必须找到适合您情况的正确方法。
Here are some generic steps to follow. Please note, these are examples, not complete code. You must find the correct ways to apply this information in your case.
首先,在WP中,将您的函数添加为ajax回调:
First, in WP, add your function as an ajax callback:
add_action ( 'wp_ajax_my_action', 'invfr_sendmail' );
// The AJAX command is 'my_action'
您必须在函数中进行一些修改。首先,在这里回荡事物不会得到答复。但是,让我们从头开始!在回调函数 invfr_sendmail
内,添加从jQuery接收表单的代码。由于它们是编码字符串,因此必须在顶部进行解析:
You must make some modifications in your function. For one, echoing things there won't give a reply. But let's start at the beginning! Inside your callback function invfr_sendmail
, add the code that receives the form from jQuery. Since they come as an encoded string, we must parse them on the top:
$my_form_data = array(); // Create an empty array
parse_str( $_POST['my_form_data'], $my_form_data ); // Fills $my_form_data
现在,而不是使用 $ _ POST ['fieldname ']
,则使用 $ my_form_data ['fieldname']
。
Now, instead of using $_POST['fieldname']
, you use $my_form_data['fieldname']
.
在PHP代码末尾,您必须将JSON编码的回复发送给jQuery。例如:
In the end of your PHP code, you must send the JSON encoded replies to jQuery. For example:
$success = true;
$errors = array( 'This one was wrong', 'That one too' );
$some_other_value = false;
// Put these variables in an array
$results = compact( 'success', 'errors', 'some_other_value' );
wp_send_json( $results );
通过AJAX发送表单并听取答案。
Send your form via AJAX and listen for the answer.
jQuery('form#my_form_name').on('submit', function(event){
event.preventDefault(); // Stops the form from being submitted via POST
var data = {
command: 'my_action', // The same name you used in WP 'add_action' above
my_form_data: jQuery('form#my_form_name').serialize()
};
jQuery('.loading').show();
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: data
}).done( function( response ) {
// This runs when the server replies something
if (response.success) {
// This corresponds to the $success variable we set
jQuery('#someElement').html('The operation was a success!')
}
if (response.errors) {
// This would be the $errors array from PHP
response.errors.each( function(errorMessage) {
jQuery('#someElement').append( errorMessage );
} );
}
if (response.some_other_value) {
// Here nothing happens if $some_other_value in PHP was false
}
}).fail( function( jqXHR, textStatus, errorThrown ) {
// This runs when the request fails (i.e. timeout)
jQuery('#someElement').html( 'The AJAX request failed with error message ' + errorThrown );
}).always( function() {
// This runs always after an AJAX request, even a failed one
jQuery('.loading').hide();
});
});
希望这个示例可以很好地帮助您使用插件!
Hope this example will set you well on your way with your plugin!