post表单与AJAX请求- WordPress插件开发



尝试在前端使用AJAX调用创建表单,用户可以在其中提交帖子。

有一个文本字段、一个文本区域和一个文件字段。

格式如下:

public function pp_html_template() {
if ( is_user_logged_in() ) {
return '<h2>' . __( 'Publish your post', 'post-publisher' ) . '</h2>
<form id="pp-form-submit" class="pp-form-submit" enctype="multipart/form-data">' .
wp_nonce_field( 'pp_publisher_save', 'pp_publisher_name' )
. '<div class="pp-row">
<label for="pp_title">' . esc_attr__( 'Title', 'post-publisher' ) . '</label>
<input type="text" id="pp_title" name="pp_title">
</div>
<div class="pp-row">
<label for="pp_content">' . esc_attr__( 'Content', 'post-publisher' ) . '</label>
<textarea name="pp_content" id="pp_content" name="pp_content" cols="30" rows="10"></textarea>
</div>

<div class="pp-row">
<label for="pp_featured_image">' . esc_attr__( 'Featured Image', 'post-publisher' ) . '</label>
<input type="file" id="pp_featured_image" name="pp_featured_image">
</div>
<input type="hidden" name="action" value="pp_html_process"/>
<div class="pp-row">
<input type="submit" name="pp_submit" id="pp_submit">
</div>
</form>';
}
}

处理过程如下:

public function pp_html_process() {
// Process the form
if ( isset( $_POST['pp_submit'] ) ) {
if ( ! isset( $_POST['pp_publisher_name'] ) || ! wp_verify_nonce( $_POST['pp_publisher_name'], 'pp_publisher_save' ) ) {
esc_attr__( 'Sorry, this action is not allowed.', 'post-publisher' );
exit;
} else {
global $current_user;
$user_login   = $current_user->user_login;
$user_id      = $current_user->ID;
$post_title   = sanitize_text_field( $_POST['pp_title'] );
$post_content = sanitize_textarea_field( $_POST['pp_content'] );
$new_post = array(
'post_title'   => $post_title,
'post_content' => $post_content,
'post_type'    => 'post',
'post_status'  => 'draft',
'post_name'    => str_replace( ' ', '-', $post_title ),
);
$post_id = wp_insert_post( $new_post, true );
if ( ! function_exists( 'wp_generate_attachment_metadata' ) ) {
require_once( ABSPATH . "wp-admin" . '/includes/image.php' );
require_once( ABSPATH . "wp-admin" . '/includes/file.php' );
require_once( ABSPATH . "wp-admin" . '/includes/media.php' );
}

$featured_image = media_handle_upload( 'pp_featured_image', $post_id );
if ( $featured_image > 0 ) {
update_post_meta( $post_id, '_thumbnail_id', $featured_image );
}
}
}
}

construct()

public function __construct() {
if ( ! is_admin() ) {
add_shortcode( 'pp_html_template', array( $this, 'pp_html_template' ) );
add_action( 'init', array( $this, 'pp_html_process' ) );
}
add_action( 'wp_ajax_pp_html_process', array( $this, 'pp_html_process' ) );
add_action( 'wp_ajax_nopriv_pp_html_process', array( $this, 'pp_html_process' ) );
}

AJAX:

jQuery(document).ready(function ($) {
$('#pp-form-submit').submit(ajaxSubmit);
function ajaxSubmit() {
var newCustomerForm = $(this).serialize();
jQuery.ajax({
type: "POST",
url: "/codeable/wp-admin/admin-ajax.php",
data: $("#pp-form-submit").serialize(),
success: function (response) {
console.log(response);
}
});
return false;
}
});

这是CURl请求:

curl 'http://localhost:8888/cdbl/wp-content/plugins/post-publisher/public/assets/js/pp-public-jq.js' 
-H 'Connection: keep-alive' 
-H 'Pragma: no-cache' 
-H 'Cache-Control: no-cache' 
-H 'sec-ch-ua: "Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"' 
-H 'sec-ch-ua-mobile: ?0' 
-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36' 
-H 'sec-ch-ua-platform: "macOS"' 
-H 'Accept: */*' 
-H 'Sec-Fetch-Site: same-origin' 
-H 'Sec-Fetch-Mode: no-cors' 
-H 'Sec-Fetch-Dest: script' 
-H 'Referer: http://localhost:8888/cdbl/' 
-H 'Accept-Language: sr-RS,sr;q=0.9,en-US;q=0.8,en;q=0.7,hr;q=0.6,sl;q=0.5,bs;q=0.4,sv;q=0.3,da;q=0.2,pt;q=0.1,fr;q=0.1,he;q=0.1' 
-H 'Cookie: wordpress_71d96747b9bfc3c631d78d4d4d334cf6=marko%7C1632206615%7CtnKvrmSveEtJFS7cJBUwaJgzn0pY2MbblA1yqLiaSQO%7Ccde31e8b50b7181062a7bb780b2cba008918b4f68b644f8ed2de71406ed4fe18; wordpress_test_cookie=WP%20Cookie%20check; wp-settings-time-1=1631803323; wp-settings-1=libraryContent%3Dbrowse; wordpress_logged_in_71d96747b9bfc3c631d78d4d4d334cf6=marko%7C1632206615%7CtnKvrmSveEtJFS7cJBUwaJgzn0pY2MbblA1yqLiaSQO%7C81060441911318c4457ead826c5a3e2aa1cf7fbe6bc8d078b3203eff43cb3178; mp_a36067b00a263cce0299cfd960e26ecf_mixpanel=%7B%22distinct_id%22%3A%20%2217bf571eeb2d11-0dbb8fc5091344-113f6757-60e640-17bf571eeb36fe%22%2C%22%24device_id%22%3A%20%2217bf571eeb2d11-0dbb8fc5091344-113f6757-60e640-17bf571eeb36fe%22%2C%22%24initial_referrer%22%3A%20%22http%3A%2F%2Flocalhost%3A8888%2Fpimodules%2Fwp-login.php%22%2C%22%24initial_referring_domain%22%3A%20%22localhost%3A8888%22%7D' 
--compressed

我在控制台中没有得到任何错误。没有AJAX的Post工作得很好,但是有了AJAX,它返回0。

任何建议都会有帮助的。

我没有你的全部代码。所以我将给出一些步骤,让你解决你的问题。您可以全部执行,也可以一步一步地执行:

<form>中加入action="POST",去除enctype="multipart/form-data">

<form id="pp-form-submit" class="pp-form-submit" action="POST">

您可以尝试使用下面的代码提交表单:

jQuery(document).ready(function ($) {
$('#pp-form-submit').submit(function (e) {
e.preventDefault();
var frmData = new FormData(document.getElementById("#pp-form-submit"));
$.ajax({
type: "post",
contentType: false,
processData: false,
url: "/codeable/wp-admin/admin-ajax.php",
data: frmData,
success: function (response) {
console.log(response);
},
error: function (req, error) {
console.log(req, error);
},
});
});
});

如果还是不行,你可以把url/codeable/wp-admin/admin-ajax.php改成像http://localhost/codeable/wp-admin/admin-ajax.php这样的全URL

您应该使用wp_localize_script将admin_ajax URL添加到javascript变量。例如:

wp_enqueue_script("your_script_name", 'full-path-to-script/script.js', array('jquery'), '1.0', true );
wp_localize_script("your_script_name", 'ajax_variables', array( 
'ajax_url' => admin_url( 'admin-ajax.php' )
));
wp_enqueue_script("your_script_name");
那么,你可以在javascript文件中使用admin-ajax URL,如:
$.ajax({
type: "post",
contentType: false,
processData: false,
url: ajax_variables.ajax_url,
data: frmData,
success: function (response) {
console.log(response);
},
error: function (req, error) {
console.log(req, error);
},
});

最新更新