如何解决Wordpress ajax不传递文本变量
我使用 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'];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。