【发布时间】:2019-09-11 01:43:35
【问题描述】:
我正在使用 Web 表单 3.5 中的 ajax 使用 Web 服务,然后将其保存到数据库中。我从 Web 服务获得了成功响应。但是,在ajax成功后,我将如何调用我的代码隐藏函数来保存数据?我是 ajax 新手。
<body>
<form id="form1" runat="server">
<div id ="divName" runat="server" class="form-group">
<label class="control-label">Name</label>
<asp:TextBox ID="txtname" CssClass="form-control" runat="server" ></asp:TextBox>
</div>
<input id="btnRegister" type="button" value="Register" /><br />
</form>
<script type ="text/javascript">
$(document).ready(function () {
$("#btnRegister").click(function () {
debugger;
var namee = document.getElementById("<%=txtname.ClientID %>").value;
Register(namee);
});
function Register(name) {
debugger;
var id =
$.ajax({
type: "POST",
url: "https://webservice.com/register",
data: JSON.stringify({
"name": name
}),
contentType: "application/json",
datatype: "json",
success: function (response) {
//call code behind function in saving data.
},
failure: function (response) {
alert("ERROR");
}
});
}
});
</script>
</body>
【问题讨论】:
-
您知道您可以使用传统帖子在您的代码中调用 Web 服务吗?如果您想调用您的代码隐藏客户端,您需要将其设置为 WebMethod,然后也使用 AJAX 调用它。
-
还要注意在 ASP.net 中这些被称为 PageMethods,更多信息在这里:dotnetcurry.com/ShowArticle.aspx?ID=109
-
@JonP,是的,我知道这一点,但是我的代码中有很多验证,所以我的方法是将 Web 服务的消费和另一个将数据保存到我的数据库的功能分开。
-
验证是好的,但是为什么在验证失败的情况下调用webservice呢?
-
@JonP,但这是程序的一部分。