【发布时间】:2018-12-20 08:52:54
【问题描述】:
我是 JavaScript 的新手,我正在尝试让用户访问以更新 WooCommerce 的产品库存。我制作了“更新”按钮来运行脚本,但它不会运行,页面只会刷新。但是当我从控制台执行脚本时,它可以工作(例如 js_update_stock('20');)
我正在修改现有的 WordPress 插件,所以如果代码有点分散,我很抱歉。如果您还需要什么,请告诉我。
HTML 方面:
<input type="number" id="stock'. $postid . '" name="stock'. $postid .'" value="'. get_post_meta( $postid, '_stock', true ) .'">
<button class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>
我把这个脚本放在同一个页面上:
echo '<script type="text/javascript">
function js_update_stock(product_id) {
var isnum = /^\d+$/.test(document.getElementById("stock" + product_id).value);
if(isnum){
if(confirm("Do you really want to update the stock of this product?")){
var data = {
action: \'update_stock\',
security: \'' . $ajax_nonce . '\',
id: product_id,
stock: document.getElementById("stock" + product_id).value
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
if(response == \'true\'){
location.reload(true);
}
});
}
else{
// do nothing
}
}
else{
alert("Please enter a valid stock quantity");
}
}
</script>';
AJAX 回调函数:
add_action('wp_ajax_update_stock', 'update_stock_callback');
function update_stock_callback() {
check_ajax_referer( 'blahblah', 'security' );
if(isset($_POST['id'])){
$id = intval( $_POST['id'] );
$stock = intval( $_POST['stock'] );
wc_update_product_stock( $id, $stock );
echo 'true';
}
else{
echo 'false';
}
die(); // this is required to return a proper result
}
感谢任何帮助,因为这已经困扰我 2 天了。谢谢。
【问题讨论】:
-
在函数顶部添加
alert行并再次尝试查看它是否被触发。我假设您的按钮位于form元素内,因此可能具有默认功能
标签: javascript ajax wordpress woocommerce