gpt4 book ai didi

javascript - AJAX 未成功从 asp.net 服务器返回

转载 作者:行者123 更新时间:2023-11-30 16:47:44 24 4
gpt4 key购买 nike

在练习 Ajax 时,我编写了一个 Ajax 调用,它向本地 asp.net Handler.ashx 发送一个带有用户名和密码的 Json,如果它们等于“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 + "\" }");

(请注意,您拼错了“application”...并且您应该告诉调用者您返回的是 json 数据。)

I saw that the Handler.ashx receives the call, does the validation, and write to response, but the Ajax call not success.

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

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

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

然后还要检查 Console 选项卡,看看是否悄悄抛出了任何 JavaScript 错误。

关于javascript - AJAX 未成功从 asp.net 服务器返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30982046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com