簡體   English   中英

在頁面加載和單擊按鈕時調用ajax函數

[英]Calling a ajax function on page load and on click of button

我有一個包含參數x的ajax函數的javascript文件。 我無法顯示該函數。我想在頁面加載和單擊按鈕時調用該函數。該函數上還有一個for循環,用於顯示變量10次,即for(i=0;i<10;i++)

該按鈕的代碼是:

HTML文件

<html>
 <title>Call web service</title>
  <head>
   <script type="text/Javascript" src="jquery-1.9.1.js"></script>
     <script type = "text/javascript" src="ajax.js"></script>
     <script type="text/javascript">

     window.onload=function()
     {
       Webservice(1)('onload');    //call 1 where webservice is ajax function 

      }


    </script>     
   </head>
 <body>
   <input id="button"  type = "button" name = "button" value = "Call Webservice" onClick = "Webservice(5)"/>
 </body>

</html>

現在,當我單擊按鈕時,我得到的是onload函數被覆蓋,而我希望同時顯示兩個函數的輸出,所以請幫助我。

提前致謝。

嘗試這樣做:

function f1() {
    //what you need to do
}
function f2() {
    //Do the same thing here also
}

這是您的JS,在onload中,調用f1() ,對於按鈕單擊,調用f2() 如果您希望f1()f2()之前執行,我建議您在這里研究鎖:

如何在JavaScript中實現鎖定

您的javaScript代碼應如下所示:

var fn = function fn(x) {
  // Do something
}

$(function() {
  var someValue;

  // someValue = ...

  // Call function once document is loaded
  fn(someValue);
  // Bind function as a callback to button click
  $('#button').on('click', function(event) {
    fn(someValue);
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM