繁体   English   中英

AJAX无法成功从ASP.NET服务器返回

[英]AJAX not success returning from asp.net server

在练习Ajax时,我编写了一个Ajax调用,该调用将使用用户名和密码的Json发送到本地asp.net Handler.ashx,如果它们等于“ jhon”“ 123456”,则返回true,否则返回false。 我调试了代码,然后看到Handler.ashx收到了调用,进行了验证,并写入了响应,但是Ajax调用未成功。

这是Ajax的调用:

$.ajax({
    url: '/Handler.ashx',
    dataType: 'json',
    data: {
        name: document.getElementById("username").value,
        password: document.getElementById("password").value
    },

    success: function (json) {
        alert(json.isvalid);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(textStatus, errorThrown);
        alert(textStatus + "  " + errorThrown);
    }
});
alert("failed");

这是服务器端:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        Console.WriteLine("check");
        var name = context.Request["name"];
        var password = context.Request["password"];

        string response = IsValid(name, password) ? "true" : "false";
        context.Response.ContentType = "appliaction/text";
        context.Response.Write("{isvalid:'" + response + "'}");
    }

    private bool IsValid(string name, string password)
    {
        Console.WriteLine("isvalid");
        return (name == "jhon" && password == "123456");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

谢谢!

最简单的更改(仍然不是很漂亮)是更改此...

string response = IsValid(name, password) ? "true" : "false";
context.Response.ContentType = "appliaction/text";
context.Response.Write("{isvalid:'" + response + "'}");

...对此...

string response = IsValid(name, password) ? "true" : "false";
context.Response.ContentType = "application/json";
context.Response.Write("{ \"isvalid\" : \"" + response + "\" }");

(请注意,您会拼写“应用程序” ...,并且应该告诉调用者,而不是返回json数据。)

我看到Handler.ashx收到了调用,进行了验证,并写入了响应,但是Ajax调用没有成功。

当您说“ AJAX呼叫不成功”时,是否出现错误?

我建议您在Google Chrome中运行您的代码,打开“开发人员选项”(按F12键),进入“网络”标签,然后刷新您的网页。

观看“网络”选项卡,单击要调用的URL,然后检查“正在发送的请求”和“响应”。

然后还要检查“控制台”选项卡,以查看是否有任何JavaScript错误被悄悄抛出。

尝试将其添加到您的ProcessRequest方法中

JavaScriptSerializer serializer = new JavaScriptSerializer();

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void ProcessRequest(HttpContext context)
    {
        Console.WriteLine("check");
        ....

        return serializer.Serialize("{ isvalid: '" + response + "' }");
    }

而在客户端

.....
success: function (msg) {
    console.log(msg); //this is for you to see the response in the JS console
    var jsonArray = $.parseJSON(msg.d);
    console.log(jsonArray); //and this is the same
    alert(jsonArray.isvalid);
}
.....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM