Execute Javascript only on page load, not PostBack (SharePoint)

故事扮演 提交于 2019-12-23 17:58:55

问题


I'm trying to execute some JavaScript on page load on a custom page on a SharePoint site (it populates the people picker with the current user). The problem is that the code executes on postback too, which I don't want as it will reset any changes to the people picker.

I've tried using if(!IsPostBack) to no avail. Everything errors out at that point, giving

SCRIPT5009: 'IsPostBack' is undefined.

I can't find anything online to help with this. Any ideas? Thanks


回答1:


You can create a function like this:

function IsPostBack() {
    var ret = '<%= Page.IsPostBack%>' == 'True';
    return ret;
}



回答2:


IsPostBack is not a javascript variable, it's a .NET webforms variable that is only available on the server so the client will complain about it. So what to do then? I suggest this mish-mash in your control's html:

<% if(IsPostBack) { %> <!-- runs on server -->

<script type="text/javascript">
 alert('will only be printed to html if not postback');
</script>

<% } %> <!-- ends server if-block -->



回答3:


You may want to try the below. Use the JavaScript pageLoad method and use the isInAsyncPostBack Property of the PageRequestManager object to determine whether it's a postback. Refer the MSDN link here for more details.

<script type="text/javascript" language="javascript">
  function pageLoad(sender, args) {
    if (!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {

     // call you JavaScript function in here

    }
  }
</script>


来源:https://stackoverflow.com/questions/26978112/execute-javascript-only-on-page-load-not-postback-sharepoint

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