Login Page using ASP.Net & Ajax

Login Page using ASP.Net & Ajax

本文关键字:amp Ajax Net Page using ASP Login      更新时间:2023-09-26

我正在尝试使用html、ajax&ASP.NET。数据确实传递给了ajax函数,但当我调试ASP页面时,用户名和密码会以NULL发送。该代码应该采用username&password然后返回userid

Html页面:

    <div id="usernameid">Username:</div><input id="username" type="text"/> <span id="username_status"></span>
    <div id="passwordid">Password:</div><input id="password" type="password"/> <span id="password_status"></span>
    <div> <input id="loginbutton" onclick="UserLogin()" type="submit" value="Submit" /></div>

Javascript:

function UserLogin() {
var postData = JSON.stringify({ "username": JSON.stringify($("#username").val()), "password": JSON.stringify($("#password").val()) });
alert(postData);
$.ajax({
    type: "GET",
    url: "http://localhost:49317/LoginPageForLearn.aspx",
    data: postData,
    contentType: "application/json; charset=utf-8",
    dataType: "jsonp",
    jsonp: 'jsoncallback',
    success: callbackfunction,
    error: function (msg) { alert(msg); }
    }); 
    }
    function callbackfunction(datacoming) {
    localStorage["UserID"] = datacoming;
    alert(datacoming);

Asp.net页面:

protected void Page_Load(object sender, EventArgs e)
    {
        string userName = "";
        int userId = -1;
        string PassWord = "";
        if (Request.QueryString.Count != 0 && Request.QueryString["username"] != string.Empty && Request.QueryString["password"] != string.Empty)
            {
                userName = Request.QueryString["username"];
                PassWord = Request.QueryString["password"];
                userId = GetUserID(userName, PassWord);
            }
    }

你知道为什么数据传递不正确吗?或者,对于如何使用html创建登录页面并在SQL中访问数据,您有其他想法吗。

非常感谢。

您可以创建一个PageMethod:

[WebMethod]
public static bool MyMethod(string username, string password)
{
    ...
    return true;
}

然后去掉双重JSON字符串化并调用页面方法:

var postData = JSON.stringify({ 
    "username": $("#username").val(), 
    "password": $("#password").val() 
});
$.ajax({
    type: "POST",
    url: "LoginPageForLearn.aspx/MyMethod",
    data: postData,
    contentType: "application/json; charset=utf-8",
    success: callbackfunction,
    error: function (msg) { alert(msg); }
}); 

在回调中,您可以测试页面方法的结果:

function callbackfunction(result) {
    if (result.d) {
        alert('success');
    }
}

它不是那样工作的。您还必须返回一些内容,以便通知客户端身份验证成功或失败。您必须考虑编程工作流程。

您可以在所调用的页面中创建一个静态方法,该方法返回Bool或JSON形式的值。大致如下:

[WebMethod] 
[ScriptMethod(UseHttpGet = true)]
public static bool Authenticate JsonMethod(int username, string password)
{ 
   bool isAuthenticated = // some method to authenticate
   return isAuthenticated;
}

你的AJAX看起来像这样:

$.ajax({
    type: "GET",
    url: "http://localhost:49317/LoginPageForLearn.aspx/Authenticate",
    data: postData,
    contentType: "application/json; charset=utf-8",
    dataType: "jsonp"
}); 

在你的成功或失败回电中,你将从那里评估你想用返回的价值做什么。

无论如何,处理程序可能会更好,因为它不包含不必要的标记。