我正在努力让ajax工作,如果有人能指导我,我将不胜感激。
我正在构建这个插件。
我有一个名为courselinkscript.js的文件,其中包含这个
jQuery(document).ready(function($){
jQuery(".courselist").change(function () {
jQuery.ajax({
type:"POST",
url: my_ajax_object.ajax_url,
data: { 'action': 'getLinkedCourses' }
//where/what do I put here to work with the data I received.
})
});
});
然后在我的主php文件course-listing.php中,我有这个
function getLinkedCourses() {
global $wpdb;
$results = $wpdb->get_results( 'SELECT list.ID, list.course, list.cost, list.length, link.CourseID FROM `wp_course_list` AS list INNER JOIN `wp_course_link` as link ON (list.ID=link.LinkID) WHERE link.CourseID = 1', OBJECT );
echo json_encode($results);
wp_die();
}
function wpb_adding_scripts() {
wp_register_script('courselinkscript', plugins_url('courselinkscript.js', __FILE__), array('jquery'),'1.0', true);
wp_enqueue_script('courselinkscript');
wp_localize_script( 'courselinkscript', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_ajax_my_list', 'getLinkedCourses' );
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
我对ajax的调用不起作用,因为我不知道需要做什么来初始化它。任何帮助都将不胜感激。
使用下面提到的代码。它应该起作用。
function getLinkedCourses() {
global $wpdb;
$results = $wpdb->get_results( 'SELECT list.ID, list.course, list.cost, list.length, link.CourseID FROM `wp_course_list` AS list INNER JOIN `wp_course_link` as link ON (list.ID=link.LinkID) WHERE link.CourseID = 1', OBJECT );
echo json_encode($results);
wp_die();
}
function wpb_adding_scripts() {
wp_register_script('courselinkscript', plugins_url('courselinkscript.js', __FILE__), array('jquery'),'1.0', true);
wp_enqueue_script('courselinkscript');
wp_localize_script( 'courselinkscript', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_ajax_getLinkedCourses', 'getLinkedCourses' );
add_action( 'wp_ajax_nopriv_getLinkedCourses', 'getLinkedCourses' );
// add_action( 'wp_ajax_my_list', 'getLinkedCourses' );
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
用以下代码替换您的javascript:
jQuery(document).ready(function($){
jQuery(".courselist").change(function () {
jQuery.ajax({
type:"POST",
url: my_ajax_object.ajax_url,
data: { 'action': 'getLinkedCourses' },
//where/what do I put here to work with the data I received.
success: function(data) {
var obj = jQuery.parseJSON(data);
console.log(obj);
},
});
});
});