TL; DR:不是Dupe - 先編碼,滾動到問題底部。WordPress AJAX請求返回0
這是the link to the demo that I currently have。
在functions.php
我第一次本地化我的腳本:
function ajaxurl(){
wp_enqueue_script('product-selector', get_template_directory_uri() . '/js/ajax.js', array('jquery'));
wp_localize_script('product-selector', 'MyAjax', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url('admin-ajax.php'),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
//'postCommentNonce' => wp_create_nonce('myajax-post-comment-nonce'),
)
);
}
add_action('wp_head', 'ajaxurl');
然後在劇本上我我的AJAX調用有:
function ajax_callback() {
global $wpdb; // this is how you get access to the database
// Declare our variable.
$cat = $_POST['cat'];
// Q the DB
$query = $wpdb->get_col($wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE post_category=%s
", $cat
));
header('Content-Type: application/json');
wp_send_json(json_encode($query));
}
add_action('wp_ajax_nopriv_ajax-callback', 'ajax_callback');
終於爲ajax.js我:
$(document).ready(function(){
var back_end_script_url = MyAjax.ajaxurl;
$(function() {
var category_callback = function(data) {
console.log(data);
var adhesion_select = $('#adhesion');
var substrate_select = $('#substrate');
substrate_select.find('option').remove();
adhesion_select.find('option').remove();
for (var k in data) {
var option = $('<option />').val(k).html(data[k]);
adhesion_select.append(option);
}
};
var adhesion_callback = function(data) {
console.log(data);
var substrate_select = $('#substrate');
substrate_select.find('option').remove();
for (var k in data) {
var option = $('<option />').val(k).html(data[k]);
substrate_select.append(option);
}
};
var category_change = function() {
console.log('Category Changed');
var category = $(this).find(":selected").val();
var params = {
action: 'ajax-callback',
cat: category
};
console.log(params);
$.post(back_end_script_url, params, category_callback);
};
var adhesion_change = function() {
console.log('Adhesion Changed');
var adhesion = $(this).find(":selected").val();
var category = $('#cat').find(":selected").val();
var params = {
action: 'ajax-callback',
cat: category,
adhesion: adhesion
};
console.log(params);
$.post(back_end_script_url, params, adhesion_callback);
};
$('#cat').on('change', category_change);
$('#adhesion').on('change', adhesion_change);
});
});
所以我的問題是,如果你看演示,ajax只返回數字0,而不是來自db的數據。
我已經閱讀了關於堆棧和wordpress交流的這個問題的所有相關問題,並嘗試了所有這些問題,結果總是相同的。
我僱傭了JS代碼,但這個人發誓我的結局。我不確定這是否屬實,因爲我在代碼中找不到任何問題。
感謝您的幫助,Stack!
需求以及工作,但PHP我的問題是'行動: ajax回調' – 2014-09-03 11:27:00