使用纯JavaScript从另一个(php)文件获取JSON? [英] Get JSON from another (php) file using pure javascript?

查看:83
本文介绍了使用纯JavaScript从另一个(php)文件获取JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javascript新手.我有一个php文件,列出了目录中的所有文件.我想调用该文件,并获取仅使用javascript回显的json数组.我知道jquery可以做到...但这是我唯一需要做的事情.它不值得学习jquery,也不想用我只打算用于这一件事的库来夸大我的页面.

I'm new to javascript. I have a php file that lists all the files in a directory. I want to call that file and get the json array that it echos using only javascript. I know jquery can do it... but this is the only thing I need to do. Its not worth learning jquery for it nor do I want to bloat my page with a library I'm only going to use for this one thing.

推荐答案

我会说仅使用jquery来处理AJAX的所有不同浏览器是一件很痛苦的事情,而且我相信您长远来看也会将其用于其他用途.

I would say just use jquery as handling all different browsers for AJAX is a pain and I am sure you will use it in the long run for other things too.

如果您真的想这样做,这里是一个本地js请求的示例:

If you really want to do this here is an example of a native js request:

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
}

您将像这样使用它:

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
  }
  else{
   alert("An error has occured making the request")
  }
 }
}

mygetrequest.open("GET", "mypage.php", true)
mygetrequest.send(null)

这篇关于使用纯JavaScript从另一个(php)文件获取JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆