[英]Call C# function (WebMethod) from Javascript (JQuery)
I have a function like this 我有这样的功能
[WebMethod]
public static string Hello()
{
return "hello";
}
I want to call it in my aspx page. 我想在我的aspx页面中调用它。 so this is what I am trying
所以这就是我正在尝试的
function sendData(){
$.post("Default.aspx/Hello", function(data){
alert(data);
}).fail(function() {
alert( "error" );
});
}
Now caling this is successful and doesn't return error, but it doesn't return what I want. 现在校准成功,不会返回错误,但是不会返回我想要的。 Instead of returning the string "hello" it gives me back a string of the html of the page
而不是返回字符串“ hello”,而是给了我该页面的html字符串
You need to use data.d
: 您需要使用
data.d
:
function sendData(){
$.post("Default.aspx/Hello", function(data){
alert(data.d);
}).fail(function() {
alert( "error" );
});
}
Dave Ward article on why you need to use .d
Dave Ward文章为何需要使用
.d
You also need to make sure that you have added a script manager and EnablePageMethods ie 您还需要确保已添加脚本管理器和EnablePageMethods,即
<asp:ScriptManager runat="server" EnablePageMethods="true">
</asp:ScriptManager>
我认为您应该在js方法中使用$ .ajax而不是$ .post,因为如果没有另外指定,则GET http方法是控制器中默认使用的方法。
I think you are close. 我觉得你很亲密。 In my project I am using $.ajax.
在我的项目中,我正在使用$ .ajax。 I have provided the code sample from my project (which works fine) and I hope it helps.
我已经提供了项目中的代码示例(效果很好),希望对您有所帮助。
C# C#
[WebMethod]
public static List<ConnectionStatusInfo> GetConnectionStatus()
{
.....
}
JavaScript JavaScript的
$.ajax({ url: "ConnectionStatus.aspx/GetConnectionStatus",
dataType: "json",
type: 'POST',
data: null,
contentType: "application/json; charset=utf-8",
success: function (data) {
},
error: function (d) {
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.