Search code examples
javascriptsharepointsharepoint-2010

Why I can't get the ClientContext by OM in JavaScript?


Here is what I did in my project:

<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript">
  alert("before");
  //It can not work cause the LIST is in the subsite called "Service"
  //var clientContext = SP.ClientContext.get_current();
  var context =new SP.ClientContext("http://sp2010dev1:88/Service/");
  alert(context );  
</script>
</asp:Content>

But, the alert(context) can not execute ,when I check the concole it showed me TypeError: SP.ClientContext is not a constructor,that is to say there was something wrong with the initialization of ClientContext. Why? How can I get ClientContext? Or was it caused by the lacking of SP.js?

My Final Solution is : Add this statement to the masterpage: ,and then everything works good! May this can help you.


Solution

  • Instead of writing directly in the <script> blocks try to insert in the function and call that function on body load.

    Another good way is call using the jquery

    $(document).ready()(function(){
    var context =new SP.ClientContext("http://sp2010dev1:88/Service/");
      alert(context );  
    
    });
    

    Try this once, even if it is not working then will try to find another solution.

    Along with this as per steve suggestion, include first sp.js and perform remaining things.