【问题标题】:calling server function from client side从客户端调用服务器函数
【发布时间】:2015-01-10 01:12:33
【问题描述】:

我需要使用 json 从客户端调用后面代码中的方法,但该方法从未被调用,并且错误“c”为空白。我在这里做错了什么?

客户端代码:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "MyPage.aspx/CheckItem",
    data: {item: item},
    dataType: "json",
    success: function (result) {
        if (result) {
            errorMessage.innerHTML = 'WARNING: Item exists.';
            return false;
        }
    },
    error: function (a,b,c) {
        alert("error: " + c);
    }
});

服务器端代码:

[System.Web.Services.WebMethod]
public static bool CheckItem(string item)
{
    DataContext dc = new DataContext();

    var record = dc.MyTable.Where(x => x.Item == item).FirstOrDefault();
    if (record != null)
        return true;
    else
        return false;
}

【问题讨论】:

  • 你不应该向MyPage.aspx/CheckItem而不是MyPage.aspx/MyMethod提出请求吗?
  • 是的,我做到了(这是一个错字)
  • 该代码在您的页面中的什么位置?您确定根本没有调用 ajax 代码吗?
  • 我放了一个断点,它转到“错误”,第三个参数(即“c”)为空白
  • 尝试在ajax请求中添加cache: false

标签: jquery asp.net json webmethod


【解决方案1】:

请用引号/双引号将您的参数括起来。请看下文。

            var item = 0;
            $.ajax({
                type: "POST",
                url: "/WebForm1.aspx/CheckItem",
                data: '{"item":"' + item +'"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (errorThrown) {

                    alert(errorThrown.responseText + "what's wrong?" + " " + errorThrown);
                },
                success: function (msg) {

                    alert(msg.d);
                    return false;
                    // Do something interesting here.
                }
            });
    [WebMethod]
    public static bool CheckItem(string item)
    {
        return true;
    }

【讨论】:

    【解决方案2】:

    如果您想在 ASP 页面中调用一个方法,您需要在 ASP 页面中添加一些逻辑来调用该函数。您不能直接从 $.ajax() 调用它。例如,您的 ajax 调用可能是:

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "MyPage.aspx",
        data: {
            item: item,
            method: 'CheckItem'
        },
        dataType: "json",
        success: function (result) {
            if (result) {
                errorMessage.innerHTML = 'WARNING: Item exists.';
                return false;
            }
        },
        error: function (a,b,c) {
            alert("error: " + c);
        }
    });
    

    然后在您的 asp 代码中,您将查找“方法”表单变量并调用指定的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-27
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-13
      相关资源
      最近更新 更多