1. 程式人生 > 其它 >jQuery load和jQuery post的使用及區別

jQuery load和jQuery post的使用及區別

舉個例子:

後端程式碼如下:

using System.Collections.Generic;
using System.Web.Mvc;

namespace _2021DemoSite.Controllers
{
    public class PostLoadDiffController : Controller
    {
        // GET: PostLoadDiff
        public ActionResult Index()
        {
            ViewBag.Tags = GetProjectTagInfosOriginal();
            
return View(); } public ActionResult TagList(string Id) { ViewBag.Tags = GetProjectTagInfoNew(); return View(); } private IList<TagInfo> GetProjectTagInfosOriginal() { var tags = new List<TagInfo>() {
new TagInfo{TagId="1",Name="AA",UsedCount=3}, new TagInfo{TagId="2",Name="BB",UsedCount=30}, new TagInfo{TagId="3",Name="CC",UsedCount=40}, }; return tags; } private IList<TagInfo> GetProjectTagInfoNew() {
var tags = new List<TagInfo>() { new TagInfo{TagId="1",Name="E",UsedCount=3}, new TagInfo{TagId="2",Name="F",UsedCount=30}, new TagInfo{TagId="3",Name="G",UsedCount=40}, }; return tags; } } public class TagInfo { public string TagId { get; set; } public string Name { get; set; } public int UsedCount { get; set; } } }

前端程式碼:

Index.cshtml

@{
    ViewBag.Title = "Index";
    string testId = "1,2,3";
}

<script src="~/Scripts/jquery-2.1.1.js"></script>
<div id="tagList">
    @Html.Partial("TagList")
</div>

<input type="button" id="btnPost" value="LoadTest" />
<input type="button" id="btnLoad" value="PostTest" />

<script>
    //重新整理tagList裡的內容,可以用load跟post
    //但load的侷限性就是當傳遞引數大於一定長度時會出現錯誤:查詢字串過長的請求,這時只能用post請求

    $("#btnPost").click(function () {
          $("#tagList").load("TagList?Id=@testId");
    });
    $("#btnLoad").click(function () {
        $.post( "TagList", { Id: "@testId" }, function (result) {
            $("#tagList").html(result);//注意這邊是用html不是用innerHTML啥的。
        })
    });
</script>

TagList.cshtml

@{
    ViewBag.Title = "TagList";
    Layout = null;
    var tagList = ViewBag.Tags;

}


<ul class="tagContainer" style="border: 1px solid;
        padding: 3px;
        width: 320px;
        height: 200px;
        overflow-y: scroll;
">
    @foreach (var item in tagList)
    {

        <li>
            <div class="tag-item" data-id="@item.TagId" data-name="@item.Name">
                <label class="checkbox-inline"><input type="checkbox" name="tagIds" data-id="@item.TagId" value="@item.TagId">@item.Name</label>
            </div>
        </li>
    }
</ul>