C# 从不同页面上的 javascript 调用页面的 webmethod
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10127937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a page's webmethod from javascript on a different page
提问by hofnarwillie
Is it possible to call a method attributed with [WebMethod] from javascript on a different page? I.e. using the following jquery ajax call from script on a page called PageTwo.aspx:
是否可以从不同页面上的 javascript 调用具有 [WebMethod] 属性的方法?即在名为 PageTwo.aspx 的页面上使用脚本中的以下 jquery ajax 调用:
$.ajax(
{
type: "POST",
url: "pageone.aspx/PageOneMethodOne",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg)
{
//something
}
}
);
PageOne.aspx.cs containing
PageOne.aspx.cs 包含
[WebMethod]
public string PageOneMethodOne()
{
return "hello world";
}
采纳答案by njebert
This is possible, as long as you specify the correct URL. Check out the following form:
只要您指定正确的 URL,这是可能的。查看以下表格:
<form id="form1" runat="server">
<div>
<div id="messages">
</div>
<input type="text" id="echo" /><input id="echoSubmit" value="Echo!" type="button"/>
</div>
and it's corresponding Javascript:
它是相应的Javascript:
<script type="text/javascript">
$(function () {
$('#echoSubmit').click(function () {
var mes = $('#echo').val();
var jsonText = JSON.stringify({ message: mes });
$.ajax({
type: "POST",
url: "SampleForm.aspx/SendMessage",
data: jsonText,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#messages").append(msg.d);
}
});
});
});
</script>
Clicking the echoSumbit button will send the contents of the input box to a WebMethod on another control, SampleForm.aspx. Here is the code-behind of that form:
单击 echoSumbit 按钮会将输入框的内容发送到另一个控件 SampleForm.aspx 上的 WebMethod。这是该表单的代码隐藏:
public partial class SampleForm : System.Web.UI.Page
{
[WebMethod]
public static string SendMessage(string message)
{
return message;
}
}
The click handler in Chat.aspx sends the input value to SampleForm.aspx.cs, which returns the sent value. The returned value is appended to a div in Chat.aspx in the success method of the .ajax call.
Chat.aspx 中的单击处理程序将输入值发送到 SampleForm.aspx.cs,后者返回发送的值。在 .ajax 调用的成功方法中,将返回值附加到 Chat.aspx 中的一个 div。

