Summary of five ways that C background calls foreground javascript

  • 2020-05-12 02:26:01
  • OfStack

After searching the Internet, I found three ways to access the foreground code:

Type 1, OnClientClick (vs2003 does not support this method)

< asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="client_click()" OnClick="Button1_Click" / >

client_click() is just one method of javascript.

The second, Button1.Attributes.Add ("onclick", "return Client_Click()");

"Client_Click()" is a foreground method that can be replaced with 1-like scripts such as: retrun confirm(' are you sure to delete? ')

The third, which I consider the most flexible, is ClientScript.RegisterStartupScript

Example: StringBuilder sb = new StringBuilder();

sb.Append(" < script language='javascript' > ");

sb.Append("Button2_onclick('" + serverPath + "')");

sb.Append(" < /script > ");

ClientScript.RegisterStartupScript(this.GetType(), "LoadPicScript", sb.ToString());

Type 4. Write scripts using the Response.Write method

For example, after you click the button, operate on the database first, and when you are done, it will show you that you have finished, and you can write in the last place you want to call

Response.Write(" < script type='text/javascript' > alert(); < /script > ");

One of the drawbacks of this method is that you can't call custom functions in the script file. You can only call internal functions. For specific functions, you can only write the function definition in Response.Write, such as Response.Write ("). < script type='text/javascript' > function myfun(){...} < /script > ");

The fifth option USES the ClientScript class to dynamically add scripts

The usage is as follows: add code where you want to call a certain javascript script function, making sure that MyFun is already defined in the script file.

ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", " < script > MyFun(); < /script > ");

This method is more convenient than Response.Write, and you can call custom functions directly from the script file.

Can be executed anywhere in the program, o(∩_∩)o... Is it working very well

Note the order of execution: execute Client first, then Server

Related articles: