问题描述
我试图将 wordpress 数据库中所有勾选的复选框的值插入到我自己创建的表中.这是我的 jQuery 代码:
I am trying to insert the values of all ticked checkboxes in a wordpress database, into a table which i created myself. Here's my jQuery code:
$(document).ready(function(){
$('#submit').click(function(){
var insert = [];
$('.get_value').each(function(){
if($(this).is(":checked") ){
insert.push($(this).val() );
}
});
insert = insert.toString();
$.ajax({
url:"insert.php",
method:"POST",
data:{insert:insert},
success:function(data){
$('.result').html(data);
}
});
});
});
和我的插入代码,(在 insert.php 中):
and my insert code, (its in insert.php):
if ( isset($_POST["insert"]) ){
global $wpdb;
$table_name = $wpdb->prefix . "status";
$wpdb->insert($table_name, array(
'status' => 'approved'
);
}
它没有显示任何错误,但也没有插入.我不知道这些信息是否有用,但复选框位于管理后端,作为自定义帖子类型的一部分.
its not showing any errors, but its not inserting either.I dont know if this information is useful, but the checkboxes are at the admin backend as part of a custom post type.
推荐答案
这行不通,因为您在 ajax 调用中调用了 insert.php
.该 url 应指向 ajaxurl,该 ajaxurl 使用您的 ajax 所在的脚本进行了本地化.
This isn't going to work, because you are calling insert.php
in your ajax call. The url should point to ajaxurl that is localized with the script where your ajax is.
因此,如果您的脚本位于名为 custom.js
的文件中,并且您将它排入队列,如下所示:
So if your script is located in file called custom.js
and you have it enqueued it like:
wp_enqueue_script( 'my_custom_script', get_template_directory_uri() . '/js/custom.js', array( 'jquery' ),'', true );
然后你将本地化你的ajax url
Then you'll localize your ajax url like
wp_localize_script( 'my_custom_script', 'ajax_call', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
) );
并在您的脚本中使用它
$(document).ready(function(){
$('#submit').click(function(){
var insert = [];
$('.get_value').each(function(){
if($(this).is(":checked") ){
insert.push($(this).val() );
}
});
insert = insert.toString();
$.ajax({
url: ajax_call.ajaxurl,
method:"POST",
data:{
'action': 'my_action_callback',
'insert': insert,
},
success:function(data){
$('.result').html(data);
}
});
});
});
你的 insert.php 代码也应该在一个钩在 wp_ajax
钩子上的函数内
Also your insert.php code should be inside a function hooked on wp_ajax
hooks
add_action( 'wp_ajax_my_action_callback', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action_callback', 'my_action_callback' );
function my_action_callback(){
if ( isset($_POST["insert"]) ){
global $wpdb;
$table_name = $wpdb->prefix . "status";
$wpdb->insert($table_name, array(
'status' => 'approved'
);
}
}
https://codex.wordpress.org/AJAX_in_Plugins
这篇关于将复选框值插入 WordPress 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!