前台JavaScript代码:
<script>
function checkLogin() {
var name = $("#name").val();
var passward = $("#password").val();
console.log(name);
console.log(passward);
$.ajax({
url: 'index.aspx?method=login',
type: 'GET',
data: { "name": name, "passward": passward },
dataType: 'json',
success: function (dataInfo) {
if (dataInfo.status) {
console.log(dataInfo.data);
//前台接收到的数据中data是字符串,需要转换为JSON对象
var jsondata = JSON.parse(dataInfo.data);
alert("登陆成功,用户名是:"+jsondata.name+" 性别是:"+jsondata.sex+" 年龄是:"+jsondata.age);
} else {
alert("登陆失败");
}
},
async: false
});
}
</script>
当然了数据获取成功之后,怎么处理自己写就好了,这里只是示范一下。
前台HTML代码:
<form id="form1" runat="server">
<div>
<input id="name" type="text" />
<input id="password" type="password" />
<button onclick="checkLogin()" value="">提交</button>
</div>
</form>
后台CS代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Runtime.Serialization;
namespace WebTest
{
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string method = Request.QueryString["method"];
string name = Request.QueryString["name"];
string passward = Request.QueryString["passward"];
if (!string.IsNullOrEmpty(method))
{
if (method == "login")
{
GetLogin(name, passward);
}
}
}
private void GetLogin(string name, string passward)
{
CommonModel msg = new CommonModel();
//这里有没有登陆成功可以连接数据库判断
if (name == "admin" && passward == "admin")
{
//这里是可以从数据库获取出来的登陆用户的信息
var jsonData = "{ \"name\":\"管理员\", \"sex\":\"男\", \"age\":\"20\"}";
msg.status = true;
msg.msg = "登陆成功";
msg.data = jsonData;
}
else
{
msg.status = false;
msg.msg = "失败";
}
object JSONObj = JsonConvert.SerializeObject(msg);
Response.Write(JSONObj);
//一定要加,不然前端接收失败
Response.End();
}
}
class CommonModel
{
//状态
private bool _statues;
public bool status
{
get { return _statues; }
set { _statues = value; }
}
//消息
private string _msg;
public string msg
{
get { return _msg; }
set { _msg = value; }
}
//数据
private object _data;
public object data
{
get { return _data; }
set { _data = value; }
}
}
}
效果图: