【发布时间】:2015-07-22 17:00:30
【问题描述】:
我正在尝试在 WordPress 上执行自定义 AJAX 操作,但它不起作用。我有以下表格:
<form method='post' name='form-bid-<?php echo get_the_ID() ?>' class="bid-form">
<input type='submit' name='<?php echo get_the_ID()?>' value='Licitar' class='bidvalue'>
<?php wp_nonce_field('ajax-bid-nonce', $post->ID); ?>
</form>
这种形式是因为它是在一个循环中生成的,网站上的每个帖子都有一个,因此我使用帖子 ID 作为输入的唯一名称。
然后,我在自定义 JavaScript 文件中捕获表单提交:
jQuery(document).ready(function($) {
// Perform AJAX bid on form submit
$('form.bid-form').on('submit', function(e) {
var action = 'ajaxbid';
var auction_id = e.target.name.substring('form-bid-'.length);
var security_container = "#".concat(auction_id);
var security = $(security_container).val();
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_bid_object.ajaxurl,
data: {
'action': action,
'id': auction_id,
'security': security
},
success: function(data) {
console.log(data);
}
});
e.preventDefault();
});
});
这部分有效,成功后在控制台打印 0。
最后,我有一个 PHP 文件,我在其中注册脚本并拥有我想在提交表单时调用的函数:
function ajax_bid_init() {
wp_register_script('ajax-bid-script', get_template_directory_uri() .'/js/ajax-bid-script.js', array('jquery') );
wp_enqueue_script('ajax-bid-script');
wp_localize_script( 'ajax-bid-script', 'ajax_bid_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
));
// Enable the user with no privileges to run ajax_bid() in AJAX
add_action( 'wp_ajax_nopriv_ajaxbid', 'ajax_bid' );
}
add_action('init', 'ajax_bid_init');
function ajax_bid() {
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-bid-nonce', 'security');
echo json_encode(array('message'=>__('SUCCESS')));
die();
}
现在,我想要的只是返回该数组并将其显示在控制台上的函数。不过这里的代码好像从来没有跑过,AJAX响应总是0。
我在网站上的登录和注册都采用了非常相似的方法,它们都有效。我已经比较了 3 次无休止的时间,我似乎找不到我在这里缺少的东西。
【问题讨论】:
-
尝试查看“网络”选项卡以获取线索:stackoverflow.com/a/21617685/2191572
-
ajax_bid_object.ajaxurl是什么我在jQuery(document).ready(function($) { /* I don't see it in here :( */ });的范围内看不到 -
网络选项卡显示一切正常,表单数据包含我想要的内容。
ajax_bid_object是包含脚本数据的变量的名称(参见link)。
标签: javascript php ajax wordpress