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>

 

posted @ 2021-08-12 15:56  katesharing  阅读(112)  评论(0)    收藏  举报