以下代码使用JSON对象,其中几个AJAX调用将数据发布到数据库的WebMethod。
我们遇到的问题是,当我单击"提交"按钮,处理数据之前的页面重新加载时,导致错误的错误,即需要@paremeter但不提供。这发生在将正在传递给ASP.NET CodeBehind处理的所有表单字段中。
我很难弄清楚为什么会发生这种情况。
有人有任何想法吗?
function getAllEmpData() {
var data = [];
$('tr.data-contact-person0').each(function () {
var ename = $(this).find('.employeename01').val();
var etitle = $(this).find('.employeetitle01').val();
var email = $(this).find('.employeeemail01').val();
var alldata = {
'emplName': ename,
'emplTitle': etitle,
'empMail': email
}
data.push(alldata);
});
console.log(data);
return data;
}
function getAllSourcepData() {
var data = [];
$('tr.data-contact-person1').each(function () {
var sname = $(this).find('.sourcename01').val();
var saddress = $(this).find('.sourceaddress01').val();
var sincome = $(this).find('.sourceincome01').val();
var alldata = {
'mySource': sname,
'mySAddress': saddress,
'mySIncome': sincome
}
data.push(alldata);
});
console.log(data);
return data;
}
function getAllSpouseData() {
var data = [];
$('tr.data-contact-person2').each(function () {
var spname = $(this).find('.spousename01').val();
var spaddress = $(this).find('.spouseaddress01').val();
var spincome = $(this).find('.spouseincome01').val();
var alldata = {
'mySpouse': spname,
'mySPAddress': spaddress,
'mySPIncome': spincome
}
data.push(alldata);
});
console.log(data);
return data;
}
function getAllDividentData() {
var data = [];
$('tr.data-contact-person3').each(function () {
var divname = $(this).find('.dividentname01').val();
var divaddress = $(this).find('.dividentaddress01').val();
var divincome = $(this).find('.dividentincome01').val();
var alldata = {
'myDivName': divname,
'myDivAddress': divaddress,
'myDivIncome': divincome
}
data.push(alldata);
});
console.log(data);
return data;
}
function getAllReimbursedData() {
var data = [];
$('tr.data-contact-person4').each(function () {
var reimname = $(this).find('.reimbursmentname01').val();
var reimaddress = $(this).find('.reimbursmentaddress01').val();
var reimincome = $(this).find('.reimbursmentincome01').val();
var alldata = {
'myReimbursName': reimname,
'myReimbursAddress': reimaddress,
'myReimbursIncome': reimincome
}
data.push(alldata);
});
console.log(data);
return data;
}
function getAllHonorariaData() {
var data = [];
$('tr.data-contact-person5').each(function () {
var honorname = $(this).find('.inputHonoraria01').val();
var alldata = {
'myHonorname': honorname
}
data.push(alldata);
});
console.log(data);
return data;
}
function getAllGiftData() {
var data = [];
$('tr.data-contact-person6').each(function () {
var gifname = $(this).find('.giftname01').val();
var gifaddress = $(this).find('.giftaddress01').val();
var gifincome = $(this).find('.giftincome01').val();
var alldata = {
'myGiftname': gifname,
'myGiftaddress': gifaddress,
'myGiftincome': gifincome
}
data.push(alldata);
});
console.log(data);
return data;
}
function getAllOrgData() {
var data = [];
$('tr.data-contact-person7').each(function () {
var orgsname = $(this).find('.orgname01').val();
var orgsaddress = $(this).find('.orgaddress01').val();
var orgsincome = $(this).find('.orgincome01').val();
var alldata = {
'myOrgname': orgsname,
'myOrgaddress': orgsaddress,
'myOrgincome': orgsincome
}
data.push(alldata);
});
console.log(data);
return data;
}
function getAllCreditorData() {
var data = [];
$('tr.data-contact-person8').each(function () {
var creditname = $(this).find('.creditorname01').val();
var creditaddress = $(this).find('.creditoraddress01').val();
var creditincome = $(this).find('.creditorincome01').val();
var alldata = {
'myCreditorname': creditname,
'myCreditoraddress': creditaddress,
'myCreditorincome': creditincome
}
data.push(alldata);
});
console.log(data);
return data;
}
$("#btnSubmit").click(function () {
var empComplete = false, sourceComplete = false, spouseComplete = false, dividentComplete = false, reimbursedComplete = false, honorariaComplete = false, giftComplete = false, orgComplete = false, creditorComplete = false;
function checkComplete() {
if (empComplete && sourceComplete && spouseComplete && dividentComplete && reimbursedComplete && honorariaComplete && giftComplete && orgComplete && creditorComplete) {
$("#result").text("All complete");
}
}
$("#result").text("");
var data = JSON.stringify(getAllEmpData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveEmpData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
empComplete = true;
checkComplete();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
var data = JSON.stringify(getAllSourcepData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSourceData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
sourceComplete = true;
checkComplete();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
var data = JSON.stringify(getAllSpouseData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveSpousData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
spouseComplete = true;
checkComplete();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
var data = JSON.stringify(getAllDividentData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveDividentData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
dividentComplete = true;
checkComplete();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
var data = JSON.stringify(getAllReimbursedData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveReimbursedData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
reimbursedComplete = true;
checkComplete();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
var data = JSON.stringify(getAllHonorariaData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveHonorariaData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
honorariaComplete = true;
checkComplete();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
var data = JSON.stringify(getAllGiftData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveGiftData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
giftComplete = true;
checkComplete();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
var data = JSON.stringify(getAllOrgData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveOrgData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
orgComplete = true;
checkComplete();
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
var data = JSON.stringify(getAllCreditorData());
console.log(data);
$.ajax({
url: 'closures.aspx/SaveCreditorData',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ 'empdata': data }),
success: function () {
creditorComplete = true;
checkComplete();
}
});
});
//codebehind上的webMethods:
<WebMethod(EnableSession:=True)> _
Public Shared Function SaveEmpData(empdata As String) As String
Dim serializedData = JsonConvert.DeserializeObject(Of List(Of Employee))(empdata)
Using con = New SqlConnection(Constr)
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim cmdGetKey As New SqlCommand("Select Max(employeeID) From Employees", con)
' Dim ID As Integer = cmdGetKey.ExecuteScalar()
For Each data As Employee In serializedData
Using cmd1 = New SqlCommand("INSERT INTO Employees(EmployeeName,empTitle,email) Values (@ename, @title,@email)")
cmd1.CommandType = CommandType.Text
cmd1.Parameters.AddWithValue("@ename", data.emplName)
cmd1.Parameters.AddWithValue("@title", data.emplTitle)
cmd1.Parameters.AddWithValue("@email", data.empMail)
cmd1.Connection = con
cmd1.ExecuteNonQuery()
Dim cmdGetKey As New SqlCommand("SELECT @@IDENTITY", con)
Dim ID As Integer = cmdGetKey.ExecuteScalar()
HttpContext.Current.Session("empID") = ID
End Using
Next
con.Close()
End Using
Return Nothing
End Function
<WebMethod(EnableSession:=True)> _
Public Shared Function SaveSourceData(empdata As String) As String
' Dim ID As Integer = HttpContext.Current.Session("empID")
Dim serializedData = JsonConvert.DeserializeObject(Of List(Of SourcDetails))(empdata)
Using con = New SqlConnection(Constr)
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim cmdGetKey As New SqlCommand("Select Max(employeeID) From Employees", con)
' Dim ID As Integer = cmdGetKey.ExecuteScalar()
For Each data As SourcDetails In serializedData
Using cmd = New SqlCommand("INSERT INTO SourceDetails(sourcename, sourceaddress, sourceincome,employeeID) VALUES(@sname, @saddress,@sincome, @ID)")
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@sname", data.mySource)
cmd.Parameters.AddWithValue("@saddress", data.mySAddress)
cmd.Parameters.AddWithValue("@sincome", data.mySIncome)
cmd.Parameters.AddWithValue("@ID", HttpContext.Current.Session("empID"))
' cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now)
cmd.Connection = con
cmd.ExecuteNonQuery()
End Using
Next
con.Close()
End Using
Return Nothing
End Function
<WebMethod(EnableSession:=True)> _
Public Shared Function SaveSpousData(empdata As String) As String
' Dim ID As Integer = HttpContext.Current.Session("empID")
Dim serializedData = JsonConvert.DeserializeObject(Of List(Of SpousDetails))(empdata)
Using con = New SqlConnection(Constr)
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim cmdGetKey As New SqlCommand("Select Max(employeeID) From Employees", con)
' Dim ID As Integer = cmdGetKey.ExecuteScalar()
For Each data As SpousDetails In serializedData
Using cmd2 = New SqlCommand("INSERT INTO SpouseDetails(spousename, spouseaddress, spouseincome,employeeID) VALUES(@spname, @spaddress,@spincome, @ID)")
cmd2.CommandType = CommandType.Text
cmd2.Parameters.AddWithValue("@spname", data.mySpouse)
cmd2.Parameters.AddWithValue("@spaddress", data.mySPAddress)
cmd2.Parameters.AddWithValue("@spincome", data.mySPIncome)
cmd2.Parameters.AddWithValue("@ID", HttpContext.Current.Session("empID"))
' cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now)
cmd2.Connection = con
cmd2.ExecuteNonQuery()
End Using
Next
con.Close()
End Using
Return Nothing
End Function
<WebMethod(EnableSession:=True)> _
Public Shared Function SaveDividentData(empdata As String) As String
' Dim ID As Integer = HttpContext.Current.Session("empID")
Dim serializedData = JsonConvert.DeserializeObject(Of List(Of DividentDetails))(empdata)
Using con = New SqlConnection(Constr)
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim cmdGetKey As New SqlCommand("Select Max(employeeID) From Employees", con)
' Dim ID As Integer = cmdGetKey.ExecuteScalar()
For Each data As DividentDetails In serializedData
Using cmd3 = New SqlCommand("INSERT INTO DividentDetails(dividentName, dividentAddress, dividentAmount,employeeID) VALUES(@divname, @divaddress,@divincome, @ID)")
cmd3.CommandType = CommandType.Text
cmd3.Parameters.AddWithValue("@divname", data.myDivName)
cmd3.Parameters.AddWithValue("@divaddress", data.myDivAddress)
cmd3.Parameters.AddWithValue("@divincome", data.myDivIncome)
cmd3.Parameters.AddWithValue("@ID", HttpContext.Current.Session("empID"))
' cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now)
cmd3.Connection = con
cmd3.ExecuteNonQuery()
End Using
Next
con.Close()
End Using
Return Nothing
End Function
<WebMethod(EnableSession:=True)> _
Public Shared Function SaveReimbursedData(empdata As String) As String
' Dim ID As Integer = HttpContext.Current.Session("empID")
Dim serializedData = JsonConvert.DeserializeObject(Of List(Of ReimbursedDetails))(empdata)
Using con = New SqlConnection(Constr)
If con.State = ConnectionState.Closed Then
con.Open()
End If
' Dim cmdGetKey As New SqlCommand("Select Max(employeeID) From Employees", con)
' Dim ID As Integer = cmdGetKey.ExecuteScalar()
For Each data As ReimbursedDetails In serializedData
Using cmd4 = New SqlCommand("INSERT INTO ReimbursementDetails(reimbursementName, reimbursementAddress, reimbursementAmount,employeeID) VALUES(@reimbursename, @reimburseaddress,@reimburseincome, @ID)")
cmd4.CommandType = CommandType.Text
cmd4.Parameters.AddWithValue("@reimbursename", data.myReimbursName)
cmd4.Parameters.AddWithValue("@reimburseaddress", data.myReimbursAddress)
cmd4.Parameters.AddWithValue("@reimburseincome", data.myReimbursIncome)
cmd4.Parameters.AddWithValue("@ID", HttpContext.Current.Session("empID"))
' cmd.Parameters.AddWithValue("@CreatedDate", DateTime.Now)
cmd4.Connection = con
cmd4.ExecuteNonQuery()
End Using
Next
con.Close()
End Using
Return Nothing
End Function
Public Class Employee
Public Property emplName() As String
Get
Return m_empName
End Get
Set(value As String)
m_empName = value
End Set
End Property
Private m_empName As String
Public Property emplTitle() As String
Get
Return m_empTitle
End Get
Set(value As String)
m_empTitle = value
End Set
End Property
Private m_empTitle As String
Public Property empMail() As String
Get
Return m_empMail
End Get
Set(value As String)
m_empMail = value
End Set
End Property
Private m_empMail As String
End Class
Public Class SourcDetails
Public Property mySource() As String
Get
Return m_mySource
End Get
Set(value As String)
m_mySource = value
End Set
End Property
Private m_mySource As String
Public Property mySAddress() As String
Get
Return m_mySAddress
End Get
Set(value As String)
m_mySAddress = value
End Set
End Property
Private m_mySAddress As String
Public Property mySIncome() As String
Get
Return m_mySIncome
End Get
Set(value As String)
m_mySIncome = value
End Set
End Property
Private m_mySIncome As String
End Class
Public Class SpousDetails
Public Property mySpouse() As String
Get
Return m_mySpouse
End Get
Set(value As String)
m_mySpouse = value
End Set
End Property
Private m_mySpouse As String
Public Property mySPAddress() As String
Get
Return m_mySPAddress
End Get
Set(value As String)
m_mySPAddress = value
End Set
End Property
Private m_mySPAddress As String
Public Property mySPIncome() As String
Get
Return m_mySPIncome
End Get
Set(value As String)
m_mySPIncome = value
End Set
End Property
Private m_mySPIncome As String
End Class
Public Class DividentDetails
Public Property myDivName() As String
Get
Return m_myDivName
End Get
Set(value As String)
m_myDivName = value
End Set
End Property
Private m_myDivName As String
Public Property myDivAddress() As String
Get
Return m_myDivAddress
End Get
Set(value As String)
m_myDivAddress = value
End Set
End Property
Private m_myDivAddress As String
Public Property myDivIncome() As String
Get
Return m_myDivIncome
End Get
Set(value As String)
m_myDivIncome = value
End Set
End Property
Private m_myDivIncome As String
End Class
您的问题可能是按钮单击会自动将<form>
提交到当前URL,该URL在执行AJAX调用之前会导致重新加载。您可以使用以下代码禁用按钮的此默认行为:
$("#btnSubmit").click(function (e) { e.preventDefault });
另外,您在发布的片段中有很多重复的代码。优化这将显着提高可读性,从而使调试方式更加容易。例如,下面的.click()
与您的代码完全相同。
$('#btnSubmit').click(function (e) {
e.preventDefault();
var posts = [{
data: getAllEmpData,
method: 'SaveEmpData'
}, {
data: getAllSourcepData,
method: 'SaveSourceData'
}, {
data: getAllSpouseData,
method: 'SaveSpousData'
} /* ... */ ];
var $result = $('#result');
$result.text('');
var calls = posts.map(function (p) {
var data = p.data();
console.log(data);
return $.ajax({
url: 'closures.aspx/' + p.method,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({'empdata': JSON.stringify(data)}),
error: function (xhr) {
alert(xhr.responseText);
}
});
});
$.when.apply($, calls).then(function() {
$result.text('All complete');
});
});