Sub*_*rat 24 javascript asp.net postback
如何在javascript中检测/跟踪/检查回发(例如在asp.net Page.isPostBack()中)?有什么建议吗?
o.k*_*k.w 39
ASPX:
<input type="hidden" id="_ispostback" value="<%=Page.IsPostBack.ToString()%>" />
Run Code Online (Sandbox Code Playgroud)
客户端脚本:
function isPostBack() { //function to check if page is a postback-ed one
return document.getElementById('_ispostback').value == 'True';
}
Run Code Online (Sandbox Code Playgroud)
PS:我还没有测试过,但我之前做过类似的事情并且有效.
Dan*_*iel 19
在某些情况下,您可能希望在没有任何服务器端代码的情况下检查回发.例如,在SharePoint中,您不能在SharePoint Designer页面中包含代码块,因此您无法使用任何需要<%= something%>的解决方案.这是一个不涉及服务器端代码的替代方案:
<script type="text/javascript">
function isPostBack()
{
return document.referrer.indexOf(document.location.href) > -1;
}
if (isPostBack()){
document.write('<span style="color:red;">Your search returned no results.</span><br/>');
}
</script>
Run Code Online (Sandbox Code Playgroud)
一个警告(或功能,取决于你如何看待它),这将不仅检测回发,而且检测页面链接到自身的任何实例.
如果要在用户单击提交按钮时检查当前页面是否为回发,则可以检查是否存在ViewState:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="xxxxx" />
Run Code Online (Sandbox Code Playgroud)
你可以使用像document.getElementById("__VIEWSTATE")
jQuery等效的东西.
但是,如果要查看当前页面是否是为响应回发而生成的,则需要先将该数据插入到服务器端的页面中.
例如:
function isPostBack() {
return <%= Page.IsPostBack %>;
}
Run Code Online (Sandbox Code Playgroud)
由于JavaScript不应该使用服务器端代码编写,并且在页面中注入新元素似乎有些过分,在我看来,最简单的解决方案是向元素添加[datat-*]
属性<head>
:
Page.Header.Attributes["data-is-postback"] IsPostBack ? "true" : "false";
Run Code Online (Sandbox Code Playgroud)
然后可以访问:
jQuery的:$('head').data('isPostback');
Run Code Online (Sandbox Code Playgroud)
香草JS:
document.head.getAttribute('data-is-postback') === 'true';
Run Code Online (Sandbox Code Playgroud)
当然,如果将[data-is-postback]
属性视为布尔属性,则可以使用:
if (IsPostBack)
{
Page.Header.Attributes.Add("data-is-postback", "");
}
else
{
Page.Header.Attributes.Remove("data-is-postback");
}
Run Code Online (Sandbox Code Playgroud)
jQuery的:
$('head').is('[data-is-postback]');
Run Code Online (Sandbox Code Playgroud)
香草JS:
document.head.hasAttribute('data-is-postback')
Run Code Online (Sandbox Code Playgroud)
小智 5
我有一个对我有用的解决方案。
// Postback catch
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function (s, e) {
alert("post back");
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
74093 次 |
最近记录: |