我通过 ajax Web 方法从 .asmx.cs 文件调用函数。现在,我在 ajax 成功中获得输出 undefined 值。
这是我的代码,
<input type="button" id="btnGetStock" value="View" class="button-89" />
$("#btnGetStock").click(function (e) {
var dataToSend = {
labelno: document.getElementById("<%=txt_labelno.ClientID%>").value
};
$.ajax({
type: "POST",
url: "FillGridMethod.asmx/QuotationList",
data: dataToSend,
dataType: "json",
success: function (data) {
alert(JSON.stringify(data.ItemType));
$("#lbl_type").val(data.ItemType);
}
});
});
这是 .asmx 文件
[WebMethod(enableSession: true)]
public void QuotationList(string labelno)
{
if (HttpContext.Current.Session["BranchId"].ToString() == null)
{
Server.Transfer("Index.aspx");
return;
}
var quotation = new List<QuotationModel>();
string constr = cn.ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
qryFillGrid = " select ItemType from tbl_StockRunning stock " + System.Environment.NewLine;
var cmd = new SqlCommand(qryFillGrid, con);
con.Open();
var dr = cmd.ExecuteReader();
while (dr.Read())
{
var quotationModel = new QuotationModel
{
ItemType = dr[0].ToString().Trim()
};
quotation.Add(quotationModel);
}
}
var js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(quotation));
}
现在,当我进行
alert(JSON.stringify(data));
警报时,我会获得正确的值,比如 [{"ItemType":"GOLD"}] 格式。但是当我做 alert(JSON.stringify(data.ItemType));
时,它变得 undefined
对象的序列化是自动的,并且开箱即用,该 Web 方法支持 SOAP、jQuery POST (AJAX),甚至 REST 调用也应该可以工作。
首先,发送的参数必须与函数签名匹配。
所以,假设我有这个:
First Name:
<asp:TextBox ID="txtFirst" runat="server" ClientIDMode="Static">
</asp:TextBox>
<br />
Last Name:
<asp:TextBox ID="txtLast" runat="server" ClientIDMode="Static">
</asp:TextBox>
<br />
<asp:Button ID="cmdWebTest" runat="server" Text="Combine aobve"
CssClass="btn"
OnClientClick="mycombine();return false;" />
<br />
Result:
<br />
<asp:TextBox ID="txtFullName" runat="server" ClientIDMode="Static">
</asp:TextBox>
<script>
function mycombine() {
var tFirst = $('#txtFirst').val()
var tLast = $('#txtLast').val()
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: '/WebService1.asmx/Combine',
data: JSON.stringify({ FirstName: tFirst, LastName: tLast }),
dataType: 'json',
success: function (mydatastuff) {
4
$('#txtFullName').val(mydatastuff.d)
},
error: function (data, success, error) {
alert("Error: " + error + " - " + data + " - " + success + " - " + data.value)
}
})
}
</script>
网页方法是这样的:
[WebMethod()]
public string Combine(string FirstName, string LastName)
{
string sResult = FirstName + " " + LastName;
return sResult;
}
注意返回数据如何嵌套在返回值的 .d 中。 (一直不喜欢这个怪癖,但这是出于安全原因)。
所以,上面的结果是这样的:
那么,要返回某个类对象的“列表”吗?
说一下这个方法:
[WebMethod()]
public List<OneHotel> GetHotels(string City)
{
DataTable rstData = new DataTable();
string strSQL =
@"SELECT * FROM tblHotelsA
WHERE City = @City AND Active = 1
ORDER BY HotelName";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
cmdSQL.Parameters.Add("@City",SqlDbType.NVarChar).Value = City;
rstData.Load(cmdSQL.ExecuteReader());
}
}
List<OneHotel> sResult = new List<OneHotel>();
foreach (DataRow dr in rstData.Rows)
{
OneHotel hotel = new OneHotel();
hotel.HotelName = dr["HotelName"].ToString();
hotel.City= dr["City"].ToString();
hotel.Description= dr["Description"].ToString();
sResult.Add(hotel);
}
return sResult;
}
因此,请注意我们如何返回类对象的列表。
所以,现在客户端变成了这样:
<h3>Show hotels for what City</h3>
<asp:TextBox ID="txtCity" runat="server" ClientIDMode="Static">
</asp:TextBox>
<asp:Button ID="cmdGetHotels" runat="server" Text="Get Hotels"
OnClientClick="showhotels();return false;"
/>
<script>
function showhotels() {
var tCity = $('#txtCity').val()
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: '/WebService1.asmx/GetHotels',
data: JSON.stringify({ City : tCity}),
dataType: 'json',
success: function (mydatastuff) {
var mytable = $('#myhotels')
$.each(mydatastuff.d, function (index, obj) {
var newRow = $("<tr>").appendTo(mytable)
$("<td>").text(obj.HotelName).appendTo(newRow)
$("<td>").text(obj.City).appendTo(newRow)
$("<td>").text(obj.Description).appendTo(newRow)
})
}
,
error: function (data, success, error) {
alert("Error: " + error + " - " + data + " - " + success + " - " + data.value)
}
})
}
</script>
<br />
<br />
<br />
<table id="myhotels" class="table table-bordered table-hover"
style="width:30%">
<tr>
<th>Hotel Name</th>
<th>City</th>
<th>Description</th>
</tr>
</table>
现在的结果是这样的: