How to update a specific div with ajax and jquery

前端 未结 2 537
夕颜
夕颜 2021-01-23 15:02

I\'m working on site and it has a fram. think of the gmail frame. And much like the gmail app I want only the inner div to be updated when clicking links on the navbar. I\'ve go

2条回答
  •  渐次进展
    2021-01-23 15:27

    I don't like to answer with links, nor just text, so here is an example of how can you make a div/table or mostly any html container to change it's content.

    If you're using MVC with Razor it'd look like this

    TestView.cshtml

    @using (Ajax.BeginForm("Test",
                           "TestController", 
                           new AjaxOptions {
                               HttpMethod = "GET",
                               InsertionMode = InsertionMode.Replace,
                               UpdateTargetId = "searchResults" }))
    {
        Search User by ID: 
        
    }
    
    

    TestController.cs

    public class TestController : Controller
    {
        public PartialViewResult Test(int id)
        {
            var model = myDbContext.Users.Single(q => q.UserID == id);
    
            return PartialView("_PartialViewTest", model);
        }
    }
    

    _PartialViewTest.cshtml

    @model IEnumerable
    
    
    
        @foreach(var item in Model) {
            
        }
    
    Name Email
    @item.Name @item.Email

    ...and if you want to do it using classic ASP.NET, it'd be like this:

    TestPage.aspx

    
        

    Scripts.js / TestPage.aspx

    function testCall() {
        $.ajax({
            url: "TestHandler.ashx",
            dataType: 'json',
            success: callbackTestCall
        });
    };
    
    function callbackTestCall(payload) {
        document.getElementById("ajaxResult").innerHTML = payload;
    };
    

    TestHandler.ashx

    public class TestHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            Random random = new Random();
    
            string actualData = random.Next(2001).ToString();
    
            context.Response.ContentType = "text/plain";
            context.Response.CacheControl = "no-cache";
    
            context.Response.Write(jss.Serialize(actualData));
        }
    
        public bool IsReusable
        {
            // Whether or not the instance can be used for another request
            get { return true; }
        }
    }
    

    If you need further information please, let me know.

提交回复
热议问题