我已经编写了此Ajax代码以将数据发送到Web服务asmx。它可以工作,但是只需单击一下,它就可以多次插入数据,有时需要2,3次单击才能插入数据。
.js
<script type="text/javascript">
function save()
{
$("button").click
(
function()
{
$.post
(
"http://localhost:82/ws/himher.asmx/InsertUsers",
{name: txtUserName.value, pwd: txtUserPwd.value},
//
);
}
);
}
</script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<label>User Name</label>
<input id="txtUserName" type="text" class="form-control" />
</div>
</div>
<div class="row">
<div class="col-md-12">
<label>Password</label>
<input id="txtUserPwd" type="text" class="form-control" />
</div>
</div>
<br/>
<div class="row">
<div class="col-md-12">
<button type="submit" onclick='save()' class="btn btn-primary pull-right">Register</button>
</div>
</div>
</div>
.cs:
public class himher : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
//[ScriptMethod(UseHttpGet = false)]
public string InsertUsers(string name, string pwd)
{
try
{
basicoperation bop = new basicoperation();
return bop.insertUsers(name, pwd);
}
catch (Exception ex)
{
throw ex;
}
}
public string insertUsers(string Name, string Password)
{
string status;
String ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(ConStr); // to make a connection with DB
SqlCommand sqlCom = new SqlCommand("InsertUsers", sqlCon); // now in order to perform action such as insert SP, we must create command object which needs command name and conncetion only
sqlCom.CommandType = CommandType.StoredProcedure; // you must tell the system that insertInfo is a storedprocedure
SqlParameter sqlParamName = new SqlParameter("@UserName", Name);
SqlParameter sqlParamPwd= new SqlParameter("@Password", Password);
sqlCom.Parameters.Add(sqlParamName);
sqlCom.Parameters.Add(sqlParamPwd);
try
{
sqlCon.Open();
int i= sqlCom.ExecuteNonQuery(); // executenonquery is used for INSERT, UPDATE, DELETE
//sqlCom.ExecuteScalar(); // used to pick or read a single value from procedure
// Response.Write("Done");
sqlCon.Close();
status= "Success";
}
catch (Exception ex)
{
//response.Write(ex.Message);
status = ex.Message;
}
return status;
}
}
最佳答案
您有两个保存功能的绑定,当您单击按钮时,其中一个已绑定。像这样重写您的JS:
<script type="text/javascript">
function save()
{
$.post(
"http://localhost:82/ws/himher.asmx/InsertUsers",
{name: txtUserName.value, pwd: txtUserPwd.value}
);
}
</script>
这样,您的
save
函数将只保存逻辑。通过<button type="submit" onclick='save()'>
用HTML完成绑定以调用此函数。关于javascript - 为什么我的按钮单击多次执行?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45385972/