【问题标题】:How to make jQuery.ajax call in external reusable javascript file in WordPress?如何在 WordPress 的外部可重用 javascript 文件中调用 jQuery.ajax?
【发布时间】:2020-02-11 12:00:14
【问题描述】:

问题

我在文件add-cp-modal.js 中有一个名为dbInsertCostPlace(nameText) 的函数,该函数调用文件wpdb-helper.js 中名为dbInsertCostPlace(onSuccess, onError) 的另一个函数,该函数调用jQuery.ajax。但是,当它位于单独的文件wpdb-helper.js 中时,ajax 调用不起作用。 ajax 调用仅在与调用它的函数位于同一文件中时才有效。

文件

add-cp-modal.js,在wpdb-helper.js中调用ajax函数:

<div id="add-costplace-modal" class="add-costplace-modal-background">

    <div class="add-costplace-modal">

      <div class="add-costplace-modal-headerr">
        <div class="add-costplace-modal-headerr-left-box">
          Skapa kostnadsställe
        </div>
      </div>

      <div class="add-costplace-modal-body">

        <div class="add-costplace-modal-name-form">

          <div class="add-costplace-modal-name-form-label">
            Namn:
          </div>
          <input id="add-costplace-modal-name-textfield" type="text" class="add-costplace-modal-name-textfield">

        </div>

      </div>

      <div class="add-costplace-modal-footer">
        <button id="add-costplace-modal-save-button">Spara</button>
        <button id="add-costplace-modal-cancel-button">Avbryt</button>
      </div>

    </div>

  </div>

  <script>

    document.addEventListener('DOMContentLoaded', function () {
      addCpModal.init();
    }, false);

    var addCpModal = {

      init: function() {
        this.addButtonListeners();
      },

      addButtonListeners: function() {
        document.getElementById("add-costplace-modal-save-button").addEventListener("click", this.savePressed);
        document.getElementById("add-costplace-modal-cancel-button").addEventListener("click", this.cancelPressed);
      },

      savePressed: function() {
        var nameText = addCpModal.getNameText();
        addCpModal.dbInsertCostPlace(nameText);
        addCpModal.hide();
      },

      dbInsertCostPlace: function(nameText) {
        wpdbhelper.dbInsertCostPlace(addCpModal.onCostPlacePostSuccess, addCpModal.onCostPlacePostError);
      },

      onCostPlacePostSuccess: function(result) {
        alert("onCostPlacePostSuccess");
        addCpModal.loadCostPlaces();
      },

      loadCostPlaces: function(){
        wpdbhelper.loadCostPlaces(addCpModal.onCostPlacesGetSuccess, addCpModal.onCostPlacesGetError);
      },

      onCostPlacesGetSuccess: function(result) {
        alert("onCostPlacesGetSuccess");
        cpTable.setData(result);
      },

      onCostPlacesGetError: function(jqXHR, textStatus, errorThrown) {
        alert("Error occurred getting cost places.");
      },

      onCostPlacePostError: function(jqXHR, textStatus, errorThrown) {
        alert("Error occurred posting cost place.");
      },

      getNameText: function() {
        var nameTextfield = document.getElementById("add-costplace-modal-name-textfield");
        return nameTextfield.value;
      },

      hide: function() {
        var modal = document.getElementById("add-costplace-modal");
        modal.style["visibility"] = "hidden";
      },

      cancelPressed: function() {
        addCpModal.hide();
      },

      show: function() {
        var modal = document.getElementById("add-costplace-modal");
        modal.style["visibility"] = "visible";
      }

    };

</script>

wpdb-helper.js包含ajax调用函数:


<script>

  var wpdbhelper = {

    dbInsertCostPlace: function(onSuccess, onError) {
      console.log("wpdb-helper: ajaxurl: " + ajaxurl);
      jQuery.ajax({
        url : ajaxurl,
        type: 'POST',
        data: {
          'action': 'insert_costplace',
          'data': {
            'name': nameText,
            'age': 17
            }
        },
        success: function(result) {
          console.log("SUCCESS");
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.log("ERROR");
        }
      });
      console.log("wpdb-helper: After ajax call.\n");
    },

    loadCostPlaces: function (onSuccess, onError){
        console.log("loadCostPlaces called inside wpdbhelper");
        jQuery.ajax({
          url : ajaxurl,
          type: 'POST',
          data: {
            action: 'get_costplaces'
          },
          dataType: 'json',
          success: function(result) {
            console.log("SUCCESS");
          },
          error: function(jqXHR, textStatus, errorThrown) {
            console.log("ERROR");
          }
        });
      }

  };

</script>

【问题讨论】:

  • 这取决于你如何声明你的第三方库......似乎jQuery 没有在全球范围内定义。也许您可以尝试传递 jQuery 实例 - dbInsertCostPlace: function(jQuery, onSuccess, onError) 并使用 dbInsertCostPlace($, onSuccess, onError) 调用它
  • @ymz 首先我在 wpdb-helper 中打印了 jQuery,但它没有被定义。我还尝试按照您的建议传递 jQuery 对象,但在运行 ajax 调用时仍然没有发生任何事情。
  • 我还没有阅读整个内容,但看起来您有一个包含 HTML 的 *.js 文件......?那是行不通的。或者你的意思是写add-cp-modal.php
  • @ChrisG 不,它是一个 .js 文件。我对javascript很陌生。 javascript 在
  • 除非您使用特殊的框架,否则您不能将任何 HTML 放入 *.js 文件中,甚至 &lt;script&gt; 标记也不行。一个 JS 文件包含 JS,并且只有 JS。如果您需要将 HTML 和 JS 同时添加到 wordpress 页面,则需要使用模板系统添加 HTML 并单独添加脚本。上面的脚本肯定会导致浏览器控制台中出现解析错误。

标签: javascript jquery ajax wordpress


【解决方案1】:

我发现了问题,现在感觉很傻。变量“nameText”未定义。我忘记将它作为参数传递给 wpdp-helper 方法。一旦我传入了 nameText 值,ajax 调用就起作用了。

【讨论】:

    【解决方案2】:

    基于这个简短(但很棒)article

    使用wp_enqueue_script("jquery");在页脚(而不是页眉)中包含您的 jQuery 定义

    您还可以添加一个匿名范围(同样,在页脚中)以使用 $ 而不是 jQuery 使用:

    (function($) {
    
        // $ Works! You can test it with next line if you like
        // console.log($);
    
    })( jQuery ); 
    

    这应该使 jQuery 在项目中的所有文件中可见

    【讨论】:

    • 我也试过了。没用。未定义 jQuery 没有任何问题。但是由于某种原因调用 jQuery.ajax(),它什么也没做。没有错误,没有日志,什么都没有。
    • 在这种情况下,检查您的网络流量(使用您的浏览器开发工具 - 例如:developers.google.com/web/tools/chrome-devtools/network)并验证您的 ajax 调用是否记录在那里并且具有正确的值(也许 ajaxurl 不是在您的外部文件中正确定义)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    相关资源
    最近更新 更多