Wordpress ajax 没有传递文本变量
Wordpress ajax not passing text variable
我使用来自 wordpress 官方网站的 ajax 代码。如果我发送数字,一切正常,如果我发送文本变量,它不会发送?
如果我用数字更改文本,一切正常并存储在数据库中,如果我输入文本,它会发送 0。
index.php
<?php
add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here
function my_action_javascript() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 12345,
'notes': sometext, / Text is not sent???
'courseid': 666555444
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script> <?php
}
function.php
<?php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$notes = intval( $_POST['notes'] );
$course_id = intval( $_POST['courseid'] );
$whatever += 10;
echo $whatever;
global $wpdb;
$wpdb->insert(
$wpdb->prefix. 'lms_enroll',
[
'course' => $notes,
'student' => $whatever,
'course_ID' => $course_id,
]
);
wp_die(); // this is required to terminate immediately and return a proper response
}
您的代码存在问题,您正在将 $_POST['notes']
中的字符串转换为整数:
$notes = intval( $_POST['notes'] );
只需删除对 intval
的调用即可按预期获取字符串:
$notes = $_POST['notes'];
我使用来自 wordpress 官方网站的 ajax 代码。如果我发送数字,一切正常,如果我发送文本变量,它不会发送?
如果我用数字更改文本,一切正常并存储在数据库中,如果我输入文本,它会发送 0。
index.php
<?php
add_action( 'admin_footer', 'my_action_javascript' ); // Write our JS below here
function my_action_javascript() { ?>
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 12345,
'notes': sometext, / Text is not sent???
'courseid': 666555444
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script> <?php
}
function.php
<?php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$notes = intval( $_POST['notes'] );
$course_id = intval( $_POST['courseid'] );
$whatever += 10;
echo $whatever;
global $wpdb;
$wpdb->insert(
$wpdb->prefix. 'lms_enroll',
[
'course' => $notes,
'student' => $whatever,
'course_ID' => $course_id,
]
);
wp_die(); // this is required to terminate immediately and return a proper response
}
您的代码存在问题,您正在将 $_POST['notes']
中的字符串转换为整数:
$notes = intval( $_POST['notes'] );
只需删除对 intval
的调用即可按预期获取字符串:
$notes = $_POST['notes'];