简体   繁体   中英

load user control dynamically with ajax AND have jquery document ready functionality

I have a user control that will load via

public static string RenderControl(Control control)
{
    var controlWriter = new StringWriter();
    var htmlWriter = new Html32TextWriter(tw);
    control.RenderControl(writer);
    htmlWriter.Close();            
    return controlWriter.ToString();
}

AJAX used to write the html

$('#testDiv').html(result.d);

This is called through an ajax Post. It loads the user control fine, but since the javascript document load has already fired I cannot use jquery's document.Ready.

My situation is I need to load a user control dynamically and have jquery document.ready fire , or some equivalent. I would rather not use an updatepanel but if that is the only means of getting this done then that is what I will use.

What is an elegant solution to my problem?

You can use the built-in jQuery ajaxStop event to fire when an ajax call completes.

http://api.jquery.com/ajaxStop/

I solved something similar with a custom event that fires after the ajax contents were loaded and displayed.

Trigger the event inside the ajax function, after load and display:

$(document).trigger('ajaxLoadCallback');

And catch it in your document.ready script:

$(document).on('ajaxLoadCallback', function() {
    // Your ready functions
}

If you create a function for everything that should be executed after document.ready than you can call this function (eg readyFunctions() ) on document.ready and after the firing custom event.

public partial class Default : Page 
{
  [WebMethod]
  public static string GetDate()
  {
    return DateTime.Now.ToString();
  }
}

$(function(){
$.ajax({
  type: "POST",
  url: "Default.aspx/GetDate",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(msg) {
    // Do something interesting here.
  }
});
});

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