在C中从JavaScript调用服务器端方法#

在C中从JavaScript调用服务器端方法#,javascript,c#,Javascript,C#,我想从JavaScript调用一个C#server方法。在JavaScript函数中,将发出警报,但不调用服务器方法 这是我的密码。这是服务器端方法: public void ReloadData() { //here is the code } 以下是客户端功能: function GetData() { alert("Function called"); PageMethods.ReloadData(); } 现在,这里调用了getdata函数,同时也会发出警报,但在服务器端没

我想从JavaScript调用一个C#server方法。在JavaScript函数中,将发出警报,但不调用服务器方法

这是我的密码。这是服务器端方法:

public void ReloadData()
{
     //here is the code
}
以下是客户端功能:

function GetData() {
alert("Function called");
PageMethods.ReloadData();
}

现在,这里调用了
getdata
函数,同时也会发出警报,但在服务器端没有调用方法。[我已经在调试模式下看到了这一点。]

我相信您必须使用AJAX来实现这一点。请看这里:

在代码隐藏中,重载数据将是一种webmethod,其外观如下所示:

[System.Web.Services.WebMethod]
public void ReloadData()
{
     //here is the code
}
function GetData() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/ReloadData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
var xhr = new XMLHttpRequest();
xhr.open('GET', 'CS.aspx/ReloadData');
xhr.onload = function() {
    if (xhr.status === 200) {
        alert('Successful');
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();
然后从客户端执行如下操作:

[System.Web.Services.WebMethod]
public void ReloadData()
{
     //here is the code
}
function GetData() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/ReloadData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
var xhr = new XMLHttpRequest();
xhr.open('GET', 'CS.aspx/ReloadData');
xhr.onload = function() {
    if (xhr.status === 200) {
        alert('Successful');
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();
}

CS.aspx
是您的网页名称

下面是您的评论;如果您不想使用JQuery,那么您的Javascript代码将如下所示:

[System.Web.Services.WebMethod]
public void ReloadData()
{
     //here is the code
}
function GetData() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/ReloadData",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
var xhr = new XMLHttpRequest();
xhr.open('GET', 'CS.aspx/ReloadData');
xhr.onload = function() {
    if (xhr.status === 200) {
        alert('Successful');
    }
    else {
        alert('Request failed.  Returned status of ' + xhr.status);
    }
};
xhr.send();

是否可以使用javascript?@s.k.Soni您可以使用javascript进行AJAX调用。JavaScript代码在客户端浏览器中运行,而C代码在服务器上。HTTP(AJAX)是这两个环境的通信方式。@s.k.Soni,我已经更新了代码。您是否在问,如果没有JQuery,是否可以执行此操作?可能重复的nope这不是重复的,因为这里调用了javascript,但没有进入服务器端方法。请再次读取它。一天结束时,您正在使用客户端脚本向某些服务器资源发出请求。
Web表单
PageMethods
作为您可以使用的选项,并且需要一些设置。@s.k.Soni您使用的是asp.net吗?是的@roxy'pro。。。。