我正在使用 ASP.NET Web 表單技術和 jquery ajax 處理這個示例場景:在輸入文本元素上的更改事件中,必須將 ajax 請求發送到 asp.net 頁面(Login.aspx/GetDoublicate)中的代碼后面的函式以檢查資料庫中是否存在電子郵件并回傳真或假。我的代碼:
<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;
}
之后我得到這個: 結果
并在使用控制臺記錄回應后,我不僅列印了 true 或 false 的頁面整個元素,這意味著我不需要成功呼叫該函式。
我嘗試使用 WebMethod 裝飾但同樣的失敗結果指出我需要從 DB 獲取資料,而靜態方法無法做到這一點。
我嘗試使用更新面板并將隱藏的 ASP 按鈕放入其中,因此當(更改事件發生在 Text2 上)我使用 jquery .click 方法單擊隱藏按鈕但我也無法得到任何結果。
提前感謝大家。
uj5u.com熱心網友回復:
經過數小時的嘗試和研究,我找到了解決方案,這是我的完整代碼:
$(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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/352757.html
