ASP.net Javascript Postback
I'm learning javacript, and I'm about at the point where I want to start doing some asychronous stuff. Here is the gist of my quest:
I have HTML code that looks like this:
<a id='nine' onclick="SendToServer('nine');">Nine</a>
I then want a way to, in Javascript, send back to the server that a#nine was clicked.
function SendToServer(id)
{
/开发者_运维百科/Send that a#nine was clicked back to server
}
I then want some sort of handler function in c# to update an entry in a database.
public void GetMessageFromJSHandler(int id)
{
Item[x][y] = id;
}
I don't want the page to reload, I don't want anything to change on the page, and I want to do this in straight javascript so that I can learn how it works.
This is a GREAT resource: http://msdn.microsoft.com/en-us/library/ms178210.aspx I ended up altering this example for my needs. All Js and very straightforward.
Well, inside the context of your question, you're on the right track. You can use this example: http://www.devx.com/DevX/Tip/17500 to see how to populate your SendToServer function
GetMessageFromJSHandler would probably be called by the ProcessRequest method of an implementer of IHttpHandler, at least in the easiest scenario.
but that way of doing things is really for academic purposes, learning the plumbing as it were. In a production environment, you're much better off using a framework. My personal crack of choices is jquery on the client and ASP.NET MVC on the server, but if you like "regular" ASP.NET (aka webforms) then check out the MS Ajax libraries to see some easier ways of doign things in a scalable & maintainable fashion.
You can mark your page methods with a WebMethod attribute to create stubs for them on the client-side. Here is an example. Another thing you could do is make your page method static and call it using jQuery's ajax() function. Here is how this way works.
jQuery:
function SendToServer(id)
{
$.ajax({
url: "/GetMessageFromJSHandler",
type: "POST",
data: { 'id': id }
}):
}
function SendToServer(id){ var pageUrl = "SamplePage.aspx?callback=true&ItemId=" +item if (window.XMLHttpRequest) { var xmlRequest = new XMLHttpRequest(); } else { var xmlRequest = new ActiveXObject("Microsoft.XMLHTTP"); } xmlRequest.open("POST", pageUrl, false); xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlRequest.send(null); }
On pageLoad you just check the callback flag and call your function
if(Request.QueryString["callback"].ToString() == "true")
{
string id = Request.QueryString["ItemId"].ToString()
GetMessageFromJSHandler(int id);
}
精彩评论