JSON:从http检索数据

时间:2011-01-10 15:32:15

标签: javascript json

我是JSON的新手。这是我尝试从http Json检索数据的代码。但是当我运行它时它不会显示任何内容

<!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" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<script type="text/javascript">

function ajaxRequest(){
 var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE
 if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
  for (var i=0; i<activexmodes.length; i++){
   try{
    return new ActiveXObject(activexmodes[i])

   }
   catch(e){
    //suppress error
   }
  }
 }
 else if (window.XMLHttpRequest) // if Mozilla, Safari etc
  return new XMLHttpRequest()
 else
  return false
}

</script>
<title>Retrieving Json FILE</title>
</head>
<body>
<span>Demo:</span>
<div id="result"></div>

<script type="text/javascript">

var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
 if (mygetrequest.readyState==4){
  if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
   var jsondata=eval("("+mygetrequest.responseText+")") //retrieve result as an JavaScript object
   var rssentries=jsondata.items
   var output='<ul>'
   for (var i=0; i<rssentries.length; i++){
    output+='<li>'
    output+='<a href="'+rssentries[i].link+'">'
    output+=rssentries[i].title+'</a>'
    output+='</li>'
   }
   output+='</ul>'
   document.getElementById("result").innerHTML=output
   alert("it is running")
  }
  else{
   alert("An error has occured making the request")
  }
 }
}

mygetrequest.open("GET", "javascriptkit.json", true)
mygetrequest.send(null)

</script>


</body>
</html>

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

如果你想这样做:

 new ajaxRequest('http://breathecast.com/lewis/xml_json.php?format=json')

...你必须真正使用这个论点:

function ajaxRequest(url){
    // Do something with URL
}

与你所拥有的相比,基本上是:

function ajaxRequest(){
    // URL is never used
}

如果您启用了注释掉的代码:

mygetrequest.open("GET", "http://breathecast.com/lewis/xml_json.php?format=json", true)
mygetrequest.send(null)

...你会看到你的剧本终于做了些什么。在我的情况下,我收到An error has occured making the request提醒,因为我的测试页面不在http://breathecast.com/,您无法使用XMLHttpRequest从其他域获取数据。