有没有一种方法可以保存一个ajax函数/调用,以便可以重复使用?

时间:2018-10-26 17:18:50

标签: javascript ajax

我正在使用JavaScript和PHP开发一个Web应用程序,发现自己一次又一次地重新编码相同的ajax调用。有没有一种方法可以将其另存为具有或不具有参数的函数,甚至可以另存为以后使用的变量?

注意:我仍在学习JavaScript,因此感谢您对我的无知所带来的宽容。

例如,代替此:

  $("body").on("click", ".all-forms-link", function() {
         $.ajax({ 
            url: "forms.php", 
            type: "post", 
            data: {formsPage: 1}, 
            success: function(data) {
                     stage.html(data)
             }

          }); 
     }); 
     //called several more times on different actions

类似的东西:

      function loadForms() {
            $.ajax({ 
            url: "forms.php", 
            type: "post", 
            data: {formsPage: 1}, 
            success: function(data) {
                     stage.html(data)
                                     }
                   }); 
                             }

  body.on("click", ".all-forms-link", function() {
        loadForms(); //or something similar
   }); 

1 个答案:

答案 0 :(得分:0)

好的。创建命名函数声明时,例如:

function foo(){
   . . .
}

您可以在需要该功能的任何地方通过名称来引用该功能。

因此,您的代码可能比显示的代码还要简单:

function loadForms() {
  console.log("AJAX Call Initiated!");
  $.ajax({ 
    url: "forms.php", 
    type: "post", 
    data: {formsPage: 1}, 
    success: function(data) {
      stage.html(data)
    }
  }); 
}

// Just refer to your function's name (don't add parenthesis after 
// the name though because we don't want to execute it with this line
// we only want to refer to it) where a function is expected.
$(document).on("click", ".all-forms-link", loadForms);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="all-forms-link">Click me</div>