我试图通过Ajax调用将数据发布到自定义表中,效果很好(在MySQL自定义表中插入了行),但在console.log
.
这是我的密码。
PHP
function create_link() {
global $wpdb;
if ( check_ajax_referer( \'create_link\', \'nonce\', false ) == false ) {
wp_send_json_error();
}
$table_name = $wpdb->prefix . "custom_table";
$result = $wpdb->insert(
$table_name,
array(
\'icon\' => sanitize_text_field($_POST[\'icon\']),
\'text\' => sanitize_text_field($_POST[\'text\']),
)
);
if ( $result == false ) {
wp_send_json_success( \'Link has been created\' );
} else {
wp_send_json_error();
}
wp_die();
}
add_action( \'wp_ajax_create_link\', \'create_link\' );
Javascript
( function( $ ) {
$( document ).ready( function() {
$( \'.ufb-create\' ).on( \'click\', \'.ufb-btn\', function( event ) {
var $button = $( this );
$button.prop(\'disabled\', true);
var data = {
\'action\' : \'create_link\',
\'nonce\' : $button.data(\'nonce\'),
\'icon\' : $(\'.icon-input\').val(),
\'text\' : $(\'.text-input\').val()
};
$.post(ajaxurl, data )
.done( function (response) {
console.log( response );
if ( response.success == true ) {
// display success message
$(\'.ufb-create-response\').html( response.data );
} else {
// display error message
$( \'.ufb-create-response\' ).html("Something went wrong");
}
// enable button
$button.prop(\'disabled\', false);
})
.fail( function(error) {
console.log(error)
});
} );
});
})( jQuery );
控制台。日志(成功)
{ "success": false }
请帮忙。
最合适的回答,由SO网友:Jacob Peattie 整理而成
最后看看你的情况:
if ( $result == false ) {
wp_send_json_success( \'Link has been created\' );
} else {
wp_send_json_error();
}
wpdb::insert()
退货
false
当出现错误时,因此只有在出现错误时才返回成功响应。你需要交换一下这句话。
if ( $result == false ) {
wp_send_json_error();
} else {
wp_send_json_success( \'Link has been created\' );
}