当在表 ( dt.Rows.Count > 0
) 中找到数据时,我尝试停止运行 JavaScript 代码。目前,代码没有在数据库中插入数据(这就是我想要的),但 JavaScript 继续运行,因为我仍然收到成功插入消息。谢谢!
HTML
<input type="button" id="btnAddConsent" value="Add Consent" onclick="insertData();" />
JavaScript
function insertData() {
var MBID = document.getElementById("txtConsentMBID").value;
var ConsentID = document.getElementById("DropDownListConsent").value;
var ConsentDate = document.getElementById("txtPatientConsentDate").value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "insertConsent.aspx?mb=" + MBID + " &ci= " + ConsentID + "&cd=" + ConsentDate, false);
xmlhttp.send(null);
ConsentID = document.getElementById("DropDownListConsent").value = "";
ConsentDate = document.getElementById("txtPatientConsentDate").value = "";
alert("Consent Added Successfully");
}
C#
using (SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Molecular"].ConnectionString))
{
MBID = Request.QueryString["mb"].ToString();
ConsentID = Request.QueryString["ci"].ToString();
ConsentDate = Request.QueryString["cd"].ToString();
con.Open();
using (SqlCommand sc = new SqlCommand(@" select * from ConsentGroup where ConsentID = @ConsentID and MBID=@MBID ", con))
{
sc.Parameters.AddWithValue("@MBID", MBID);
sc.Parameters.AddWithValue("@ConsentID", ConsentID);
//sc.Parameters.AddWithValue("@ConsentDate", ConsentDate);
//sc.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(sc);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
// this message should displayed when count is more that 1
Response.Write("alert('This Patient already has this Concent saved in the Database');");
}
else
{
using (SqlCommand sc1 = new SqlCommand(@"insert into ConsentGroup (MBID, ConsentID, ConsentDate, ConsentWithdraw, ConsentConfirm)
values('" + MBID + "','" + ConsentID + "','" + ConsentDate + "','NO','YES')", con))
{
sc1.ExecuteNonQuery();
}
}
}
con.Close();
}
最佳答案
XMLHttpRequest
有一个事件监听器 onreadystatechange
,它在 http 请求进行时被调用。当readyState为4时,请求完成。此时,您可以拦截函数返回的内容,并确定应显示哪个警报。
xmlhttp.onreadystatechange = function()
{
if (request.readyState == 4 && request.status == 200)
{
alert(request.responseText);
}
}
关于javascript - 当 C# 验证失败时停止运行 JavaScript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44002669/