开发者

JSON: retrieving data from http

I am new in JSON. This is the code that I make an attempt to retrieve data from http Json. But it doesn't display anything when I run it

<!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", "javascr开发者_JS百科iptkit.json", true)
mygetrequest.send(null)

</script>


</body>
</html>

Thanks for your help


If you want to do this:

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

... you must actually use the argument:

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

Compare with what you have, which is basically:

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

If you enable the code you commented out:

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

... you'll see your script is finally doing something. In my case, I get the An error has occured making the request alert because my test page is not located at http://breathecast.com/ and you cannot use XMLHttpRequest to fetch data from other domains.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜