简体   繁体   中英

Redirecting to a page via ajax

I am trying to Ajaxify a normal page redirect.

ASPX (View: Parent.aspx):

<a id="GetContent" href="#">Go to Content Page</a>

ASPX (View: Content.aspx):

<div id="content">
   ...
</div>

Controller (ContentController.cs):

public ActionResult Index(id)
{
    var content = _db.GetContent(id);
    return View("Content");
}

JS:

$(document).on("click", "#GetContent", function () {
        location.href = "/Index/3";
});

I tried this. This works, however, the url in the URL bar does not change.

$(document).on("click", "#GetContent", function () {
           $("#content").load("/Index/3");
    });

So when you click on the link, currently it posts back normally and then redirects to ~/Content/3 (ie no ajax). What I want is to immediately go to the Content page, and then display a loading indicator while the content is being fetched. I know I probably have to use jQuery.load() to do this, but not quite sure how to put things together.

Any help is appreciated!

I think this is what you are looking to do...

Index.aspx:

<div id="content">
   ...
</div>

<script>
    $(document).ready(function() {
      $.ajax({
        url: '/Content/Details/3', // <-- Can use @Html.ActionLink here, to utilize routing a bit.
        success: function(data) {
          $('#content').html(data);
        }
      });
    });
</script>

ContentController.cs:

public ActionResult Index(id)
{
    return View("Index");
}

public ActionResult Details(id)
{
    var content = _db.GetContent(id);
    return PartialView("_Details", content);
}

If you put a loader.gif in the div initially I think you'll get the behavior you are looking for. You'll also need to make sure you have the _Details view created, and displaying whatever is in your model ( var content ).

i would link jquery (through

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

) and then use

var checking = "<img src='ajax-loader.gif'/>";
$("#content").innerHTML=checking
$("#content").load("/content/3");

to load it in the page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM