Ajax function not saving scroll position after redirection

前端 未结 1 1969
死守一世寂寞
死守一世寂寞 2021-01-15 20:04

As the title states, I wrote an ajax function that should scroll to the position the user were before getting redirected.

I wrote an alert for test scen

相关标签:
1条回答
  • 2021-01-15 20:33

    The problem is because it's actually navigating to the link specified in the hyperlink. Then it's also trying to do the ajax request as well.

    If ajax is to be used there's no need to have a navigateURL specified, and the default behaviour of the hyperlink needs to be suppressed by the script. Otherwise you'll get a full page refresh and a jQuery ajax request simultaneously. Since you've got jQuery installed you can do this most easily like this:

    C#:

    var hl = new HyperLink();
    hl.Text = status;
    hl.ID = "myLink";
    hl.Style.Add(HtmlTextWriterStyle.Color, (disabled ? "red" : "green"));
    hl.NavigateUrl = "#";
    cell.Controls.Add(hl);
    tr.Cells.Add(cell);
    

    JS (using unobtrusive event handling):

    $(document).ready(function() {
      $("#<%= myLink.ClientID %>").click(function(event) { 
        event.preventDefault(); //stop the normal behaviour of the link
        $.ajax({
          type: "GET",
          url: "AdminListUsers.aspx?column=Disabled&direc=False&a=chstat&z=+",
          success: function() {
            window.scrollTo(window.pageXOffset, window.pageYOffset);
          }
        });
      });
    });
    

    This will stop the link from causing the whole page to be redirected, and just allow the content to be loaded via ajax.

    N.B. If you are creating multiple instances of the hyperlink in a table, you would need to use classes rather than IDs to allow jQuery to locate it.

    However, I would question what "AdminListUsers.aspx?column=Disabled&direc=False&a=chstat&z=+" actually returns. ormally an aspx page returns a whole HTML page including the <html>, <body> tags etc - if you put this inside another element such as a <div>, it makes your page invalid - you cannot nest <html> tags. If you want to use ajax, you should use a WebMethod (or other type of webservice) to return only the HTML that should actually be inserted into the element.

    0 讨论(0)
提交回复
热议问题