Tuesday, May 24, 2005

Calling a server side func in JavaScript with document.createElement('script')


CAUTION: THIS DOESN'T SEEM TO WORK ALL THE TIME.  I'VE GONE BACK TO THE HIDDEN IFRAME TECHNIQUE


The following bit of JavaScript and C# code work to gether to do
some remote scripting from the browser to the server.  Basically
some javascript function running on the client wants to call the
'ServerFunc' C# code, and pass it a single parameter named "user".


See:




// Within a javascript function that wants to call the server:

ServerCall("ServerFunc&user="+User);

// The ServerCall function calls a function in the MYPAGE.aspx on the server.

function ServerCall(call){

       var head      = document.getElementsByTagName("head")[0];

       var script    = document.createElement('script');

       script.src    = "MYPAGE.aspx?nocache="+new Date().getTime()+"&cmd="+call;

       //alert(script.src);

       script.type   = 'text/javascript';

       head.appendChild(script);

}

NOTE: The rest is C# code in the aspx. If you're not into C#, replace this with whatever you like. The ServerCall() bits should still work.

// Within MYPAGE.aspx’s Page_Load(), we find the desired function and call it.

// Long live reflection

private void Page_Load(object sender, System.EventArgs e){

       // Find and execute the command

       MethodInfo m = GetType().GetMethod("page"+Request["cmd"]);

       if (m==null)

              m = GetType().GetMethod("pageDefault");

       m.Invoke(this,null);

}

// the m.Invoke() in Page_Load() calls this function.  Note, we prepend each page

// function with the word 'page' -- this way baddies can't run arbitrary funcs

public void pageServerFunc(){

       string user = Request["user"]; // This came from the client

      

       Script.Append("alert('You can do anything in here');");

       Script.Append("SomeClientFunc('Then call a client func to wrap up!');");

       Response.Write(script.ToString());

       Response.Flush();

       Response.Close();

}

StringBuilder script = new StringBuilder();

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?