当我加载页面时,我的getall()函数没有运行,但是当我点击按钮时它会运行,有人可以告诉我为什么$(文档).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
函数
$(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
});
答案 1 :(得分: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();
});
});
答案 2 :(得分:0)
您的文档就绪功能正在运行,但您实际上并未调用该功能。你需要添加
getAll()
在ready
功能
答案 3 :(得分: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();
});