2016-08-17 45 views
-1

我需要在加載頁面期間調用GetAllProperties()函數,而不是在完全加載頁面後調用GetAllProperties()函數。如何在頁面加載時調用AJAX函數

我試過window.onload = GetAllProperties;但它沒有工作

我的代碼如下所示:

<script type="text/javascript"> 

window.onload = GetAllProperties; 


    function GetAllProperties() {  
     $.ajax({ 
      cache: false, 
      url: '/Home/GetAllProperties', 
      type: 'GET', 
      contentType: "application/json; charset=utf-8", 
      success: function (response) { 
       if (response.list.length > 0) { 
        console.log(response.list) 
        var $data = $('<table id="mytable" class="table table-striped"> </table>'); 
        var header = "<thead><tr><th>Property Name</th><th>Edit</th></tr></thead>"; 
        $data.append(header); 
        $.each(response.list, function (i, row) { 
         var $row = $('<tr/>'); 
         $row.append($('<td/>').html(row.PropertyName)); 
         $hidden = $(' <input type="hidden" name="hid" value= "' + row.PropertyId + '">'); 
         $row.append($hidden); 
         $editButton = $("<button class='editbtn' id='mybtn'>Edit</button>");  
         $row.append($editButton); 
         $deleteButton = $("<button class='deletebtn' id='delbtn'>Delete</button>");  
         $row.append($deleteButton); 
         $data.append($row); 
        });   
        $("#MyDiv").empty(); 
        $("#MyDiv").append($data); 
       } 
       else { 

       } 
      }, 
      error: function (r) { 
       alert('Error! Please try again.' + r.responseText); 
       console.log(r);  
      } 
     });  
    }  
</script> 
+0

這個問題是一樣的,你以前問的一個。如果你想添加更多的細節問題,請使用編輯按鈕。還要注意你的代碼似乎工作正常。如果它不符合您的要求,請清楚地解釋*爲什麼*即 –

回答

1

您正在使用jQuery了,所以爲什麼不綁定事件偵聽器window呢?

$(window).on("load", GetAllProperties); 
 

 
function GetAllProperties() { 
 
    alert("loaded"); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

但它甚至沒有工作:

window.onload = GetAllProperties; 
 

 
function GetAllProperties() { 
 
    alert("loaded"); 
 
}

+0

感謝您的幫助......但爲什麼表格會在頁面加載後填充? – Lucy

+0

你知道Ajax是異步的嗎?這意味着頁面將在函數執行時繼續加載。在Ajax請求完成之前,頁面可能已完成加載。 @Lucy – eisbehr

+0

不,我不..最好寫一個非常簡單的代碼 – Lucy

相關問題