110,537
社区成员
发帖
与我相关
我的任务
分享
getdata.ashx: '{"Id":"1001","name":"zhangyu","score":"87"}'
$.get("getdata.ashx",function(data){
var d = eval('('+data+')');
alert(d['Id']);
} );
//test.ashx
namespace ajax测试
{
/// <summary>
/// 摘要说明
/// </summary>
public class test : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string jsonstr=@"{Id = 1001,name= \"zhangyu\",score = 87}";
context.Response.Write(jsonstr);
//context.Response.Write("Hello World");
//这里用Hello World代替了你要的json数据串{Id = 1001,name= "zhangyu",score = 87}
}
public bool IsReusable
{
get
{
return true;
}
}
js调用:
function read_data() {
var xmlhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp) {
alert("error:cannot create xmlhttp object.");
return false;
}
xmlhttp.open("POST", "test.ashx", false);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate == 4) {
if (xmlhttp.status == 200) //状态码200表示成功
{
//alert(xmlhttp.responseText); //用于显示获取到的json格式化数据
var data = eval('(' + xmlhttp.responseText + ')');
//-----以下是通过getElementById函数修改内容----------
document.getElementById("rc1_1").innerHTML = data.name;
document.getElementById("rc19_6").innerHTML = data.id;
}
else {
alert("error: status:" + xmlhttp.status.toString());
}
}
}
xmlhttp.send();
}
--------------------------
以上是详细的实现,并没有经过封装。
使用jquery或者其他框架封装ajax的话,会简化很多,使用方便,如2楼。