【问题标题】:Can't get response from webservice无法从网络服务获得响应
【发布时间】:2017-06-24 17:51:17
【问题描述】:

这是我在 WebService.cs 中的代码

private void ResponseData(string strJSON)
{
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Flush();
    Context.Response.Write(strJSON);
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void login(string login, string password)
{
    try
    {
        objda.loginid = login;
        objda.pass = password;
        ds = objda.getadminbyusernamepass();
        if (ds.Tables[0].Rows.Count > 0)
        {
            ResponseData(@"[{""result"":""success""}]");
        }
        else
        {
            ResponseData(@"[{""result"":""failure""}]");
        }
    }
    catch (Exception ex)
    {
        ResponseData(@"[{""result"":""error"""+ex.ToString()+"}]");
    }
}

其中objda 是一个通过存储过程访问数据的对象。

这是aspx页面:

 <form runat="server" id="form1">
     <div>
         <input type="text" id="login" runat="server" /><br />
         <input type="text" runat="server" id="password"/>
         <input type="button" value="submit" onclick="sendrequest();" />
     </div>
 </form>

<script>
    function sendrequest() {
        var a = $("#login").val();
        var b = $("#password").val();
        console.log(rowID);
        $.ajax({
            url: "WebService.asmx/login",
            data: '{"login":"' + a+ '","password":"' + b+ '"}',
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset-utf-8",
            success: function (data) {
                alert("success");
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert('error: ' + xhr.status + ' ' + thrownError);
            }
        });

    }
</script>

按下按钮时出现错误 500 undefined。另外,我不想显示alert='success',而是想访问结果的值并显示它。任何建议都会有所帮助。

【问题讨论】:

  • 请检查控制台中的网络选项卡并分享错误描述是什么?
  • 尝试将 [System.Web.Script.Services.ScriptService] 添加到您的班级。这将允许从客户端调用您的方法。这是帮助我的演练。 msdn.microsoft.com/en-us/library/bb532367(v=vs.90).aspx
  • @balaji marimuthu 错误 500(内部服务器(错误)类型=xhr 启动器=jquery-1.4.1.min.js:130。
  • @rexroxm 似乎您分享了不同的消息,它应该在 Network-> 响应中显示消息描述,如“参数名称无效/缺失”

标签: c# jquery ajax web-services json.net


【解决方案1】:

login(login,password) 方法的编写方式,它说,参数可以通过使用查询字符串来提供。但是在您的 ajax 调用中,您已将数据构造为不正确的 json。尝试将您的方法签名更改为

    public class CustomerModel
    {
        public string login { get; set; }
        public string password { get; set; }
    }

    public void login(CustomerModel customerlogin)
    {
        // Code
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-14
    • 2013-11-29
    • 1970-01-01
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多