我有一个简单的代码,可以使用WebMethod通过简单的Ajax调用来更新数据库,但不会在数据库中更新。
HTML标记
<a href="#" class="newProject" id ="<%= item2 %>"><i class="fa fa-file"></i> <%= item2 %></a>
客户端方法:
<script type="text/javascript">
$(".newProject").on("click", function () {
$.ajax({
type: "POST",
url: "index.aspx/UpdateCode",
data: 'engCode=' + this.id,
success: function (response) {
// window.location.reload();
alert(response);
}
});
return false;
});
</script>
服务器端方法:
[WebMethod]
public static int UpdateCode(string Code)
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Codes"))
{
int intresult = 0;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@Mode", SqlDbType.VarChar, 50).Value = "UpdateCodes";
cmd.Parameters.Add("@Code", SqlDbType.VarChar, 50).Value = Code;
cmd.Connection = con;
try
{
con.Open();
intresult = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
ex.ToString();
}
finally
{
cmd.Dispose();
if (con != null)
{
con.Close();
}
}
return intresult;
}
}
}
它在超链接的点击事件上发布了正确的值,但没有更新数据库。
答案 0 :(得分:0)
ASP.NET WebMethods仅适用于JSON作为数据格式:
在Ajax调用中,您需要添加
dataType: "json",
并提供数据为JSON:
data: {"engCode":this.id},
答案 1 :(得分:0)
您没有以正确的格式传递数据。试试这个
<script type="text/javascript">
$(".newProject").on("click", function () {
$.ajax({
type: "POST",
url: "index.aspx/UpdateCode",
data: {Code: this.id}
success: function (response) {
// window.location.reload();
alert(response);
}
});
return false;
});
</script>
答案 2 :(得分:0)
尝试此代码......
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JavaScriptSample._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>How to call CSharp function in Ajax | JavaScript Sample</title>
<script type="text/javascript">
function getServerTime() {
/// <summary>
/// Call ServerTime web method via ajax request
/// </summary>
if (window.XMLHttpRequest) {
// for IE7+, Firefox, Chrome, Opera, Safari
this.xmlhttp = new XMLHttpRequest();
}
else {
// for IE6, IE5
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
// older version of Msxml
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
}
xmlhttp.onreadystatechange = function() {
/// <summary>
/// Display server time when success
/// </summary>
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// success Status
document.getElementById("ServerTimeResponse").innerHTML = xmlhttp.responseText;
}
}
this.xmlhttp.open("POST", "AjaxServer.asmx/ServerTime", true);
this.xmlhttp.send();
}
</script>
</head>
<body>
<form id="ServerTimeForm" runat="server">
<div>
<input id="ServerTimeButton" type="button" onclick="getServerTime();" value="Get Server Time" />
<div id="ServerTimeResponse" runat="server">
</div>
</div>
</form>
</body>
</html>