【问题标题】:Javascript working on console, but not onclick eventJavascript 在控制台上工作,但不是 onclick 事件
【发布时间】: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


【解决方案1】:

你可以使用:而不是按钮标签:

<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 返回响应。

【讨论】:

    【解决方案2】:

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

    您可以将按钮元素的类型属性指定为“按钮”,它现在将调用您的“onclick”函数。

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

    【讨论】:

      【解决方案3】:

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

      因此,为了防止这种情况,您只需将点击事件添加到您的函数并在页面卸载之前取消它:

      <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

      希望这能解决你的问题;)

      【讨论】:

        【解决方案4】:

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

        您想将按钮类型定义为按钮,这样表单就不会提交。

        <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>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-02-11
          • 2015-04-09
          • 1970-01-01
          • 1970-01-01
          • 2017-04-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多