从客户端调用服务器功能

时间:2014-11-13 01:01:02

标签: jquery asp.net json webmethod

我需要使用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;
}

2 个答案:

答案 0 :(得分:0)

请使用引号/双引号将参数括起来。请参阅下文。

            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;
    }

答案 1 :(得分:0)

如果要在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代码中,你会寻找"方法"表单变量并调用指定的方法。