这里要说明几点:
1、WebService地址必须是全称;
2、数据返回(dataType)为xml,如果要返回Json,代码需要调整;
3、参数写法看实例;
页面部分代码:
<%...@ Page Language="C#" AutoEventWireup="true" CodeFile="a.aspx.cs" Inherits="a" %>
<!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>无标题页</title>
<script src="jquery.js"></script>
</head>
<body>
<form id="form1" runat="server">
<table id="example" border="1" cellpadding="4" cellspacing="0">
<tr>
<td>标题</td>
<td>内容</td>
</tr>
</table>
<p>
<input type="button" id="btn" value="显示" /></p>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
GetWebService("/myAddress/aa.asmx/GetExample",
{title:"测试",content :"K!又是明天"},
"#example",["Title","Content"]);
});
})
function GetWebService(myUrl,dataPrams,tableId,arrFiledId){
$.ajax({
url:myUrl,
data: dataPrams,
dataType: "xml",
type: "POST",
cache: false,
success: function(xml){
AddTd(xml,tableId,arrFiledId);
},
error:function(xml,status){
alert(status);
}
});
}
function AddTd(xml,tableId,arrFiledId){
var tb=$(tableId);
//清空表,保留第一行
tb.find("tr").each(function(i){
if (i>0) $(this).remove();
});
//填充数据
$(xml).find("Table1").each(function(){
var tr=$("<tr></tr>");
for (var j=0;j<arrFiledId.length;j++)
$("<td></td>").html($(this).find(arrFiledId[j]).text()).appendTo(tr);
tr.appendTo(tb);
})
}
</script>
</form>
</body>
</html>
asmx代码:
[WebMethod]
public DataSet GetExample(String title, String content)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Title", Type.GetType("System.String"));
dt.Columns.Add("Content", Type.GetType("System.String"));
DataRow dr = dt.NewRow();
dr["Title"] = "甲方";
dr["Content"] = "好了没?";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Title"] = "乙方";
dr["Content"] = "明天!"+DateTime.Now.ToString("yyyy-M-d H:m:s");
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["Title"] = title;
dr["Content"] = content;
dt.Rows.Add(dr);
ds.Tables.Add(dt);
return ds;
}