JQuery ajax读取asp.Net 的 json,XML数据
<title>无标题页</title>
<script src="../JS/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Button1").click(function(){
$.ajax({
url:'Data.aspx',
type: 'GET',
dataType: 'json',
timeout: 1000,
cache:false,
error:erryFunction,///错误执行方法
success:succFunction///成功执行方法
})
function erryFunction (){
alert("error");
}
function succFunction (tt){
var json = eval(tt);数组
$.each(json,function(index,item) {///循环获取数据
var name = json[index].Name;
var age =json[index].Age;
$("#ddd").html($("#ddd").html()+"<b>用户名:" + name + " 年龄:" + age + "</b>");
});
}
});
})
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="button" id="Button1" value="点击我" />
<div id="ddd">
</div>
</form>
</body>
</html>
Data.aspx 页面
protected void Page_Load(object sender, EventArgs e)
{
List<Customer> list = new List<Customer>();
Customer c = new Customer();
c.Name = "张三";
c.Age =23;
list.Add(c);
Customer cc = new Customer();
cc.Name = "李四";
cc.Age = 25;
list.Add(cc);
Response.ContentType = "application/json";
Response.Write(new JavaScriptSerializer().Serialize(list));这个很关键,否则error
Response.End();
}
ajax 读取XML数据
///xml数据
$("#Button2").click(function(){
$.ajax({
url:'DataXML.aspx',
type: 'GET',
dataType: 'xml',
timeout: 1000,
cache:false,
error:erryFunction,
success:succFunction,
beforeSend:bsFunction,
complete:comFunction
})
function erryFunction (){
alert('加载XML文档出错');
}
function succFunction (xml){
//建立一个代码片段
var frag=$("<ul/>");
//遍历所有student节点
$(xml).find("Student").each(function(i){
//获取Name节点
var name=$(this).children("Name")
///获取Age节点
var age=$(this).children("Age")
//获取节点文本
//获取student下的email属性。
//email=$(this).attr("email");
//构造HTML字符串,通过append方法添加进之前建立代码片段
frag.append("<li>"+name.text()+"-"+age.text()+"</li>");
});
alert(frag.html());
//最后得到的frag添加进HTML文档中
frag.appendTo("#Div1");
}
function comFunction(XMLHttpRequest, textStatus){
$(".quick-alert").remove();
}
function bsFunction()
{
$('<div class="quick-alert"></div>')
.insertAfter( $("#Button2") )
.fadeIn('slow')
.animate({opacity: 1.0}, 3000)
.fadeOut('slow', function() {
$(this).remove();
});
}
});
})
'DataXML.aspx' 页面
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.DataSetName = "Students";
dt.Columns.Add("Name");
dt.Columns.Add("Age");
dt.TableName = "Student";
for (int i = 0; i < 20; i++)
{
DataRow dr = dt.NewRow();
dr["Name"] = "LI" + i;
dr["Age"] = 23 + i % 3;
dt.Rows.Add(dr);
}
ds.Tables.Add(dt);
Response.ContentType = "application/xml";
Response.Write(ds.GetXml());
Response.End();
}
原帖地址:http://djy252.blog.163.com/blog/static/103428383201011924026609/