简体   繁体   中英

Calling code behind method from javascript?

I have method in code behind:

protected void myMethod()
    {
        Literal1.Text = System.DateTime.Now.ToString();
    }

I need to call this method every second. I found that i should use javascipt, here's my scipt:

<script>
   function test() {
      // ???
   }
   setInterval(test, 1000);
</script>

but i don't know how to call myMethod from javascript?

Use AJAX. https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started This will allow you to call a designated server-side method from the client.

From the link above:

function makeRequest(url) {
    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } 
      catch (e) {
        try {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch (e) {}
      }
    }

    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    httpRequest.onreadystatechange = alertContents;
    httpRequest.open('GET', url);
    httpRequest.send();
  }

  function alertContents() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {
        alert(httpRequest.responseText);
      } else {
        alert('There was a problem with the request.');
      }
    }
  }
})();

You'll have to decorate your server-side method with the [WebMethod] attribute and declare it as public and static. http://msdn.microsoft.com/en-us/library/byxd99hx(v=vs.90).aspx

From MSDN:

[System.Web.Services.WebMethod(EnableSession=true)]
public int GetNumberOfConversions()
{
   return (int) Session["Conversions"];
}

It's that easy.

I have to question calling a method from client to server every second, however. You can handle that date business in JavaScript alone. Making a round-trip is not going to work out well for you, I'm betting.

If you want to avoid the server round-trip, which you might because of network delay, you can use javascript like so

var now = new Date();
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");// Saturday, June 9th, 2007, 5:46:21 PM

Check out http://blog.stevenlevithan.com/archives/date-time-format to see what other type of date formats are possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM