Javascript可在控制台上运行,但不能在onclick事件上运行

时间:2018-07-12 08:03:06

标签: javascript ajax wordpress woocommerce

我对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天了。谢谢。

4 个答案:

答案 0 :(得分:1)

默认情况下,按钮的类型为“提交”,因此它正在提交表单,这就是页面刷新的原因。

您要将按钮类型定义为按钮,以便表单不提交。

<button type="button" class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>

答案 1 :(得分:1)

页面正在刷新,因为我猜您正在使用的按钮位于表单中。因此,当您单击它时,它将启动对表单的请求并离开页面。

因此,为防止这种情况,您只需要在函数卸载前将click事件添加到函数中并取消它即可:

<button class="button button-primary" 
 style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" 
 onclick="js_update_stock(event, \''. $postid .'\')">
      '. __('Update','update_button') .'
</button>

对于javascript:

function js_update_stock(e, product_id) {
    e.preventDefault();
    // more code...

Javascript event prevent default on W3schools

我希望这可以解决您的问题;)

答案 2 :(得分:0)

对于大多数新浏览器,按钮元素的默认类型为“提交”。 这意味着,单击它时,将在调用“ onclick”函数之前提交表单。另外,您的表单中可能没有指定的动作属性,这就是表单向自身提交的原因。

您可以将按钮元素的type属性指定为“ button”,现在它将调用“ onclick”功能。

有关根据浏览器的按钮默认类型的更多信息,请访问: What is the default button type?

答案 3 :(得分:0)

您可以使用:

代替按钮标签
<a href='javascript:void(0);' id='updateBtn' class='btn btn-default'>Update</a>

$(document).ready(function () {
  $('#updateBtn').on('click', function () {
    // Make AJAX call here.  
    // Your logic will come here.
    $.ajax({
      url: 'Add url here',
      data: 'Add data which is need to be update in json',
      type: 'POST',
      dataType: 'json',
      success: successCallback,
      complete: completeCallback,
      error: errorCallback
    })
  });

  var successCallback = function () {
                         // AJAX success callback
                       }

  var completeCallback= function () {
                         // AJAX complete callback
                       }
  var errorCallback= function () {
                         // AJAX error callback
                       }
});

注意:另外,还要确保您没有从后端(PHP)重定向,而只是通过statusCode给出响应。

相关问题