ajax调用Web Api中的字符串不匹配

时间:2013-09-23 06:12:36

标签: jquery asp.net-web-api

我对WebAPI方法进行了ajax调用,如下所示:

function GetGroupDetails(Id, StudentType, GrpID) {
    var result = "";
    $.ajax({
        url: GetGrpDetails + Id + "&studenttype=" + StudentType + "&GrpId=" + GrpID, dataType: 'json',
        success: function (data) { if (data != null && data != "") { result = data; } },
        error: function (XHR, textStatus, errorThrown) { alert(textStatus + ":" + errorThrown); }
    });
    return result;
}

以下是转到WebAPI的网址

/api/Students/GetGroups?Id=107&studenttype="Captain"&GrpId=88

在调试过程中,如果StudentType =“Captain”中的值为“\”Captain \“”。 现在在调试器中,如果我用“Captain”替换它,它可以正常工作。

实际的WebApi是对EF上下文对象的简单LINQ查询,如果字符串符合预期,它将返回有效值,否则为null。

那么,我如何根据需要获取字符串。

问候。

2 个答案:

答案 0 :(得分:1)

您正在查看VS Debugger中的值。字符串的实际值为"Captain"。我认为字符串的正确值应该是Captain而没有任何双引号。所以修复你的客户端AJAX调用。

请求应如下所示:

/api/Students/GetGroups?Id=107&studenttype=Captain&GrpId=88

所以基本上你的StudentType javascript变量需要修复。另外我建议您传递这样的参数以确保正确的编码:

function GetGroupDetails(id, studentType, grpID) {
    $.ajax({
        url: GetGrpDetails,
        data: { id: id, studentType: studentType, grpId: grpID },
        success: function (data) {  
            if (data != null && data != "") { 
                // Do something with the data here but do not attempt to assign
                // it to some external variable that you will be returning
            } 
        },
        error: function (XHR, textStatus, errorThrown) { 
            alert(textStatus + ":" + errorThrown); 
        }
    });
}

关于代码的另一个注意事项是从GetGroupDetails函数返回一个值。您正在进行AJAX调用,并且在成功回调中,您要为从函数返回的结果变量赋值。这显然不起作用,因为AJAX是异步的,并且在成功回调执行时,该函数将很久就完成运行。因此,永远不要尝试从AJAX调用返回任何值。在里面使用它。

答案 1 :(得分:0)

删除网址中的引号,您的请求网址不应该包含它。试试这个

/api/Students/GetGroups?Id=107&studenttype=Captain&GrpId=88

和你编写的函数,永远不会返回除“”之外的任何值,尝试在ajax调用的success方法中调用所需的函数,在那里你将获得响应。

希望这有帮助。