动态创建 json 对象,包含ajax下调用josn对象

来源:互联网 发布:arraylist和数组 编辑:程序博客网 时间:2024/06/06 16:25

<!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>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Ajax Hello World</title>

<script language="JavaScript" type="text/javascript">
/*
var data={'网站':['moreyin.com','51js.com','phpchina.com'],
'类别':['网站建设','脚本编程论坛','php论坛']};
alert (data.网站[0]);
*/
</script>

<script type="text/javascript">
var xmlHttp;

function createXMLHttpRequest(){
     if(window.ActiveXObject){
         xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
     }
     else if(window.XMLHttpRequest){
         xmlHttp = new XMLHttpRequest();
     }
}

function startRequest(){
     createXMLHttpRequest();
     try{
         xmlHttp.onreadystatechange = handleStateChange;
         xmlHttp.open("GET", "data.txt", true);
         xmlHttp.send(null);   
     }catch(exception){
         alert("您要访问的资源不存在!");
     }
}

function handleStateChange(){   
     if(xmlHttp.readyState == 4){       
         if (xmlHttp.status == 200 || xmlHttp.status == 0){
             // 取得返回字符串
             var resp = xmlHttp.responseText;
             // 构造返回JSON对象的方法
    // function表示这是一个对象, return + resp  表示利用字符串构造对象
             var func = new Function("return "+resp);
    // 也可以用eval 来进行对象定义
    // eval( "var json=" + resp);
             // 得到JSON对象
             var json =  func( );
   
             // 显示返回结果
             alert("JSON's value: " + json.info + "(" + json.version + "v)");
         }
     }
}
</script>
</head>
<body>
    <div>
        <input type="button" value="return ajax JSON's value"
                 onclick="startRequest();" />
    </div>
</body>
</html> 

原创粉丝点击