jQueryload()方法是一種簡單但函數非常強大的AJAX方法。 jQuery 中的Load() 方法有助於從服務器加載數據並將其返回到所選元素,而無需加載整個頁麵。
用法:
$(selector).load(URL, data, callback);
參數:該方法接受如上所述和如下所述的三個參數:
- URL:用於指定需要加載的URL。
- data:它用於指定與請求一起發送的一組查詢鍵/值對。
- callback:它是可選參數,是調用load()方法後要執行的函數名稱。
示例 1:geeks.txt 文件存儲在服務器上,單擊按鈕後將加載該文件。 geeks.txt的內容是:Hello GeeksforGeeks!
HTML
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#div_content").load("gfg.txt");
});
});
</script>
<style>
body {
text-align: center;
}
.gfg {
font-size: 40px;
font-weight: bold;
color: green;
}
.geeks {
font-size: 17px;
color: black;
}
#div_content {
font-size: 40px;
font-weight: bold;
color: green;
}
</style>
</head>
<body>
<div id="div_content">
<div class="gfg">
GeeksforGeeks
</div>
<div class="geeks">
A computer science portal for geeks
</div>
</div>
<button>
Change Content
</button>
</body>
</html>
輸出:
參數中還有一個額外的回調函數,該函數將在 load() 方法完成時運行。該回調函數具有三個不同的參數:
- 參數1:如果方法調用成功,它包含內容的結果。
- 參數2:它包含調用函數的狀態。
- 參數3:它包含 XMLHttpRequest 對象。
示例 2:單擊該按鈕後將出現一個警告框,如果內容加載成功,則會顯示“內容加載成功!”消息。否則,它將顯示錯誤消息。
HTML
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#div_content").load("gfg.txt", function (response,
status, http) {
if (status == "success")
alert("Content loaded successfully!");
if (status == "error")
alert("Error: " + http.status + ": "
+ http.statusText);
});
});
});
</script>
<style>
body {
text-align: center;
}
.gfg {
font-size: 40px;
font-weight: bold;
color: green;
}
.geeks {
font-size: 17px;
color: black;
}
#div_content {
font-size: 40px;
font-weight: bold;
color: green;
}
</style>
</head>
<body>
<div id="div_content">
<div class="gfg">
GeeksforGeeks
</div>
<div class="geeks">
A computer science portal for geeks
</div>
</div>
<button>
Change Content
</button>
</body>
</html>
輸出:
相關用法
- JQuery load()用法及代碼示例
- JQuery last()用法及代碼示例
- JQuery live()用法及代碼示例
- JQuery length用法及代碼示例
- JQuery andSelf()用法及代碼示例
- JQuery change()用法及代碼示例
- JQuery each()用法及代碼示例
- JQuery end()用法及代碼示例
- JQuery fadeOut()用法及代碼示例
- JQuery height()用法及代碼示例
- JQuery innerHeight()用法及代碼示例
- JQuery keydown()用法及代碼示例
- JQuery keypress()用法及代碼示例
- JQuery next()用法及代碼示例
- JQuery nextAll()用法及代碼示例
- JQuery parent()用法及代碼示例
- JQuery parents()用法及代碼示例
- JQuery prev()用法及代碼示例
- JQuery prevAll()用法及代碼示例
- JQuery remove()用法及代碼示例
- JQuery show()用法及代碼示例
- JQuery toArray()用法及代碼示例
- JQuery width()用法及代碼示例
- JQuery addBack()用法及代碼示例
- JQuery addClass()用法及代碼示例
注:本文由純淨天空篩選整理自kundankumarjha大神的英文原創作品 jQuery load() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。