javascript 在javascript中触发自动回发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5009508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:38:49  来源:igfitidea点击:

trigger automatic postback in javascript

javascriptasp.netajax

提问by Ryan

I do not have access to the <body>tag because it is in masterpage. I want to trigger an automatic postback when the page load as:

我无权访问该<body>标签,因为它在母版页中。我想在页面加载为时触发自动回发:

<script type="text/javascript">
       window.onscroll=  __doPostBack("<%= button.ClientID %>", "");
</script>

where should I put this code? I get a Not implemented JS error if I place it just before the </asp:Content>tag.

我应该把这段代码放在哪里?如果我将它放在</asp:Content>标签之前,我会收到一个 Not implementation JS 错误。

Any idea how I should do this ?

知道我应该怎么做吗?

PS: I need to trigger that postback because I want to populate an updatepanel when the page loads

PS:我需要触发回发,因为我想在页面加载时填充更新面板

回答by Shadow Wizard is Ear For You

You can have such code and place it anywhere:

您可以拥有这样的代码并将其放置在任何地方:

<% if (!Page.IsPostBack) { %>
<script type="text/javascript">
window.onload = function() {
   __doPostBack("<%= button.ClientID %>", "");
}
</script>
<% } %>

Assuming you're using C# - if you have VB.NET the syntax will be bit different.

假设您使用的是 C# - 如果您使用的是 VB.NET,则语法会有所不同。

Edit: to avoid using <%and %>you can have this in the Page_Load of your page:

编辑:为了避免使用<%%>您可以在页面的 Page_Load 中使用它:

if (!Page.IsPostBack) {
   this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "auto_postback", "window.onload = function() { __doPostBack(\"" +  button.ClientID + "\", \"\"); }; ", true);
}

Edit II: alternative way with better chance of working is to have such JS code instead:

编辑二:有更好工作机会的替代方法是使用这样的 JS 代码:

"window.onload = function() { var buttonID = '" +  button.ClientID + "'; alert('ID: ' + buttonID + ', clicking...'); document.getElementById(buttonID).click(); }; "

This will hopefully show you the client ID of the button then auto click it. If no luck make sure the ID is correct and really exist in the document and we'll try to find what is the problem.

这有望向您显示按钮的客户端 ID,然后自动单击它。如果没有运气,请确保 ID 正确并且确实存在于文档中,我们将尝试找出问题所在。