客戶端代碼
$("#imgLogin").click(function () {
debugger;
var name = $("#txtName").val();
var pwd = $("#txtPwd").val();
var validate = $("#txtValidate").val();
$.ajax({
type: "post",
url: "Login.asmx/UserLogin",
data: JSON.stringify({ "_name": name, "_pwd": pwd, "_validate": validate }),
contentType: "application/json;charset=utf-8",
dataType:"json",
success: function (value) {
if (value == "1") {
alert("登陸成功");
}
},
error: function () {
alert("系統錯誤");
}
});
});
服務器端代碼:
[WebMethod(EnableSession = true)]
public string UserLogin(string _validate,string _name,string _pwd)
{
int flag = 0; //flag為0表示驗證碼錯誤,為1表示登陸成功,為2表示密碼錯誤
if (_validate.ToUpper() == Session["code"].ToString().ToUpper())
{
try
{
string _sqlStr = "select * from [user] where name='" + _name + "' and pwd='" + _pwd + "'";
DBHelper _helper = new DBHelper("sqlConStr");
if (_helper.ExecuteQuery(_sqlStr).Rows.Count>0)
{
Session["userName"] = _name;
Session["userID"] = _helper.ExecuteQuery(_sqlStr).Rows[0]["ID"].ToString();
flag = 1;
}
else
{
flag = 2;
}
}
catch (Exception _exception)
{
flag = 2;
throw _exception;
}
}
else
{
flag = 0;
}
return "{'flag':" + flag.ToString() + "}";
//return flag.ToString();
}
JSON解析的時候字符串需要用雙引號,單引號會引起解析出錯。你可以按F12打開浏覽器的開發者工具看看控制台是否有錯誤。
改成return "{""flag"":" + flag.ToString() + "}";試試