2014-03-31 76 views
-2

當我加載頁面時,我的getall()函數不能運行,但是當它點擊按鈕時它會運行,有人可以告訴我爲什麼$(document).ready不能立即運行?

$(document).ready(function() { 
function getAll() { 
    $.ajax({ 
     type: "GET", 
     url: "/Home/GetComment", 
     data: "{}", 
     success: function (model) { 

     alert("hello") 
     }, 
     error: alert("eitthvað fór úskeiðis, reyndu aftur síðar"), 
     dataType: "JSON" 
    }); 
} 

$("#button").click(function (evt) { 
    var comment = document.getElementById('CommentText').value; 
    $.ajax({ 
     type: "POST", 
     url: "/Home/Index", 
     data: { "CommentText": comment }, 
     success: function() { 
      getAll(); 
      $("#CommentText").val("") 

     }, 
     dataType: "JSON" 
    }); 
    evt.preventDefault(); 
}); 
}); 
+0

你應該打電話給你的功能,使其工作。 –

回答

1

你是不是調用它,只是定義;調用它的定義等之後:

$(document).ready(function() { 
    function getAll() { 
     $.ajax({ 
      type: "GET", 
      url: "/Home/GetComment", 
      data: "{}", 
      success: function (model) { 

       alert("hello") 
      }, 
      error: alert("eitthvað fór úskeiðis, reyndu aftur síðar"), 
      dataType: "JSON" 
     }); 
    } 

    getAll(); 

    $("#button").click(function (evt) { 
     var comment = document.getElementById('CommentText').value; 
     $.ajax({ 
      type: "POST", 
      url: "/Home/Index", 
      data: { 
       "CommentText": comment 
      }, 
      success: function() { 
       getAll(); 
       $("#CommentText").val("") 

      }, 
      dataType: "JSON" 
     }); 
     evt.preventDefault(); 
    }); 
}); 
1

你必須調用你的函數的$(document).ready功能

$(document).ready(function() { 
function getAll() { 
    $.ajax({ 
     type: "GET", 
     url: "/Home/GetComment", 
     data: "{}", 
     success: function (model) { 

     alert("hello") 
     }, 
     error: alert("eitthvað fór úskeiðis, reyndu aftur síðar"), 
     dataType: "JSON" 
    }); 
    getAll()//Call your function 
}); 
+0

super bro ... +1 –

+0

@CJRamki謝謝:-) –

0

您的文檔準備功能工作裏面,但你沒有實際調用該函數。您需要添加

getAll()

某處後在ready功能

0

嘗試

function getAll() { 
    $.ajax({ 
     type: "GET", 
     url: "/Home/GetComment", 
     data: "{}", 
     success: function (model) { 

     alert("hello") 
     }, 
     error: alert("eitthvað fór úskeiðis, reyndu aftur síðar"), 
     dataType: "JSON" 
    }); 

$(function(){ 

getAll(); 

}); 
相關問題