WebService 的常见问题
首先是 写 WebMethod
WebService.cs
/// <summary> /// 按分类和关键字查询商品 /// </summary> /// <param name="categoryId"></param> /// <param name="keyword"></param> /// <returns></returns> [WebMethod] public DataTable GetGoodsByCategoryKey(string categoryId, string keyword) { string strWhere = "1=1"; if (categoryId != "0") { string sonCategoty = Common.GetSonCategory(Util.GetInt(categoryId), "") + categoryId; strWhere += " AND CategoryId IN(" + sonCategoty + ")"; } if (!Util.IsEmpty(keyword)) { strWhere += " AND GoodsNO LIKE '%" + keyword + "%' or GoodsName LIKE '%" + keyword + "%'"; } DataSet ds = new SQLServerDAL.A_GoodsInfo().GetDataSet(null, strWhere.ToString(), "SortIndex ASC"); DataTable table = null; if (ds.Tables[0].Rows.Count > 0) { //table = Detect.ListToDataTable(PublicGoodsList(strWhere.ToString(), ds.Tables[0])); table = ds.Tables[0]; } //Detect.GetDistinctTable(ds.Tables[0], "SpareInt2"); return table; }
不要忘了引用:using Microsoft.Web.Script.Services;
然后再aspx 上写入
1 <asp:ScriptManager ID="ScriptManager1" runat="server"> 2 <Services> 3 <asp:ServiceReference Path="http://www.cnblogs.com/WebService.asmx" /> 4 </Services> 5 </asp:ScriptManager>
然后js 就可以调用了:
方法一:
1 function searchItem() 2 { 3 var cat=document.getElementById('DDL_Seach_Category'); 4 var catId=cat.options[cat.selectedIndex].value; 5 var keyword = document.forms['theForm'].elements['keyword'].value; 6 WebService.GetGoodsByCategoryKey(catId,keyword, 7 function(result) 8 { 9 var sel = document.forms['theForm'].elements['result']; 10 sel.length = 0; 11 12 /* 创建 options */ 13 if(result!=null){ 14 var Text = result.dataArray.substring(0, result.dataArray.length - 1); 15 var Table = eval(Text); 16 17 for (x = 0; x < Table.length; x++) { 18 var Row = Table[x]; 19 var option = document.createElement("option"); 20 option.text =Row.GoodsName; 21 option.value = Row.GoodsId; 22 if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) 23 sel.add(option); 24 else 25 sel.add(option, null); 26 } 27 } 28 else{ 29 alert("没有该类商品!"); 30 } 31 }) 32 }
方法一 有时会出现 返回的 result 中 没有 dataArray 的问题,导致数据显示不出来(据说 是调用的的一个库的问题)
方法二:
function searchItem() { var cat = document.getElementById('DDL_Seach_Category'); var catId = cat.options[cat.selectedIndex].value; var keyword = document.forms['theForm'].elements['keyword'].value; WebService.GetGoodsByCategoryKey(catId, keyword, function (result) { var sel = document.forms['theForm'].elements['result']; sel.length = 0; /* 创建 options */ if (result != null) { for (x = 0; x < result.rows.length; x++) { var option = document.createElement("option"); option.text = result.rows[x].GoodsName; option.value = result.rows[x].GoodsId; if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) sel.add(option); else sel.add(option, null); } } else { alert("没有该类商品!"); } }) }
换成方法二 就解决了,如果哪位也遇到这种情况!麻烦给我说下为什么?