我正在使用 ASP.NET Web 表单技术和 jquery ajax 来处理这个示例场景: 在输入文本元素上的更改事件上,必须将 ajax 请求发送到 asp.net 页面 (Login.aspx/GetDoublicate) 中代码后面的函数,以检查数据库中是否存在电子邮件并返回 true 或 false。 我的代码:
<form id="form1" runat="server">
<div>
<table style="width:100%;" dir="rtl">
<tr>
<td class="auto-style1">user name</td>
<td class="auto-style1">
<input id="Text1" type="text" /></td>
<td class="auto-style1"></td>
</tr>
<tr>
<td class="auto-style1">password</td>
<td class="auto-style1">
<input id="Password1" type="password" /></td>
<td class="auto-style1"></td>
</tr>
<tr>
<td class="auto-style1">
confirm password</td>
<td class="auto-style1">
<input id="Password2" type="password" /></td>
<td class="auto-style1"></td>
</tr>
<tr>
<td>
email</td>
<td>
<input id="Text2" runat="server" type="email" /></td>
<td> </td>
</tr>
<tr>
<td>
birth</td>
<td>
<input id="Text3" type="date" /></td>
<td> </td>
</tr>
<tr>
<td>
<input id="Button1" type="submit" value="Subscripe" /></td>
<td> </td>
<td> </td>
</tr>
</table>
</div>
</form>
<div id="fffg">
</div>
ajax请求代码
<script>
$(document).ready(function () {
$('#Text2').change(function () {
$.ajax({
type: "GET",
url: "Login.aspx/GetDoublicate",
'data': {"email":$('#Text2').val() },
//contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (response) {
console.log(response);
}
});
})
})
</script>
Login.aspx页面后台代码:
public bool GetDoublicate()
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string sqltext = "select id from CoAuthor where email='" + Request.Params["email"] + "'";
SqlCommand cmd = new SqlCommand(sqltext, con);
string x = cmd.ExecuteScalar().ToString();
con.Close();
if (string.IsNullOrEmpty(x))
{
return true;
}
else return false;
}
在使用控制台记录响应后,我打印了页面的整个元素,不仅是真或假,这意味着我不需要成功调用该函数。
我尝试使用 WebMethod 装饰,但同样的失败结果,指出我需要从数据库获取数据,而静态方法无法做到这一点。
我尝试使用更新面板并将隐藏的 ASP 按钮放入其中,因此当( Text2 上发生更改事件)我使用 jquery .click 方法单击隐藏按钮时,但也无法得到任何结果。
提前感谢大家。
经过几个小时的尝试和研究,我找到了解决方案,这是我的完整代码:
$(document).ready(function () {
$('#Text2').change(function () {
var ema = $('#Text2').val();
$.ajax({
type: "POST",
url: "Login.aspx/GetDoublicate",
// data: '{"email":'+$('#Text2').val()+ ',}',
data: JSON.stringify({ "email":ema }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// console.log(response.d);
if(response.d == true)
{ alert("doublicate email discovered"); }
else {alert("Ok, go on")};
}
,
error: function (xhr, err) { alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status + "\nresponseText: " + xhr.responseText); }
});
})
})
注意 jSon 参数必须与称为参数的函数同名。
这里是ASP代码:
[WebMethod]
public static bool GetDoublicate(string email)
{
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string sqltext = "select id from CoAuthor where email='" + email + "'";
SqlCommand cmd = new SqlCommand(sqltext, con);
SqlDataReader dr= cmd.ExecuteReader();
while (dr.Read())
{
return true;
}
con.Close();
return false;
}