How to execute javascript function from code-behind but only after the page loads

£可爱£侵袭症+ 提交于 2021-01-29 03:30:34

问题


I've found other solution on how to executes a javascript function from code-behind. The problem is that it firing before the page loads, so I can't add logic to it.

if(result)
{
   Page.ClientScript.RegisterClientScriptBlock(typeof(Page), 
                                               "Script", "confirmPwdChange();", true);
}

On the client side

<script>
   confirmPwdChange()
   {
     alert("Password has been successfully changed.");
     //Add more logic here, after user clicks the OK button...
   }
</script>

No Jquery, if possible.

Thanks for helping.


回答1:


You might want to include the window.onload in your script file. something like this..

StringBuilder script = new StringBuilder();
script.Append("var existingHandler = window.onload;");
script.Append("window.document.body.onload = function(){ confirmPwdChange(); if (existingHandler){ existingHandler()}}");
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), 
                                           "Script", script.ToString(), true);

this ensure, your change password is called on page load and retains any other existing handlers declared already on the page.




回答2:


I think you're looking for PageRequestManager

List of PageRequestManager events

var prm = Sys.WebForms.PageRequestManager.getInstance();

// beginRequest: before postback to server
prm.add_beginRequest(BeginRequestHandler);

// endRequest: after postback to server
prm.add_endRequest(EndRequestHandler);

function BeginRequestHandler(sender, args) {
    // do stuff
}

function EndRequestHandler(sender, args) {
    // do stuff
}


来源:https://stackoverflow.com/questions/40335594/how-to-execute-javascript-function-from-code-behind-but-only-after-the-page-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!