1.WebService代码
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetObject()
{
User user = new User()
{
UserID = ,
UserName = ""
};
//直接用json.net框架序列化
return JsonConvert.SerializeObject(user); }
2.jQuery代码
$(document).ready(function () {
var btn = document.getElementById("btnQ");
btn.onclick = function () {
Ajax(); }
});
function Ajax() {
$.ajax({
type: "POST",
contentType: "application/json",
url: "WebService.asmx/GetObject",
dataType: "json",
success: function (data) {
var ruleListTemp = "<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">";
//注:从WebService获取json格式为
//{"d":"{\"UserID\":1,\"UserName\":\"1111\"}"}
//所以要加一步操作
var json = jQuery.parseJSON(data.d);
$.each(json, function (n, value) {
ruleListTemp += ("<tr><td>" + value);
ruleListTemp += ("</td></tr>");
});
ruleListTemp += ("</table>"); $("#ruleList").html(ruleListTemp); } });
}
3.html代码
<input id="btnQ" type="button" value="请求数据"/>
<div id="ruleList"> </div>