函数hr.open(“POST或获取”,“URL”,“布尔”)我可以打开php文件吗?

时间:2014-07-28 05:10:37

标签: javascript php ajax json

当我将函数hr.open("POST or Get", "URL", "Boolean").json文件一起使用时,它可以正常工作。当我使用.php文件时,我似乎无法打开.php文件,但我不知道会发生什么。

这是我的HTML代码。

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax_get_json(){
    var results = document.getElementById("results");
    var hr = new XMLHttpRequest();
    hr.open("GET", "555.json", true);
    hr.setRequestHeader("Content-type", "application/json", true);
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var data = JSON.parse(hr.responseText);
            results.innerHTML = "";
            for(var obj in data){
                results.innerHTML += data[obj].user+" is "+data[obj].age+" and lives in "+data[obj].country+"<hr />";
            }
        }
    }
    hr.send(null);
    results.innerHTML = "requesting...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>

它适用于此代码,但当我将555.json函数中的hr.open更改为554.php时,结果是“请求...”

这是我的PHP代码:

<?php
header ("Content-Type : application/json ");
$Jsondata = '{ 
  "u1":{ "user":"John", "age":22, "country":"United States" },
  "u2":{ "user":"Will", "age":27, "country":"United Kingdom" },
  "u3":{ "user":"Abiel", "age":19, "country":"Mexico" }, 
  "u4":{ "user":"Rick", "age":34, "country":"Panama" },
  "u5":{ "user":"Susan", "age":23, "country":"Germany" },
  "u6":{ "user":"Amy", "age":43, "country":"France" },
  "u7":{ "user":"Pete", "age":18, "country":"Italy" },
  "u8":{ "user":"Chris", "age":25, "country":"United States" },
  "u9":{ "user":"Louis", "age":31, "country":"Spain" },
  "u10":{ "user":"Emily", "age":38, "country":"Uraguay" },
  "u11":{ "user":"Shawn", "age":52, "country":"Chile" },
  "u12":{ "user":"Greg", "age":24, "country":"Romania" }
} ' ;
echo $Jsondata;
?>

这是我的JSON:

{ 
  "u1":{ "user":"John", "age":22, "country":"United States" },
  "u2":{ "user":"Will", "age":27, "country":"United Kingdom" },
  "u3":{ "user":"Abiel", "age":19, "country":"Mexico" }, 
  "u4":{ "user":"Rick", "age":34, "country":"Panama" },
  "u5":{ "user":"Susan", "age":23, "country":"Germany" },
  "u6":{ "user":"Amy", "age":43, "country":"France" },
  "u7":{ "user":"Pete", "age":18, "country":"Italy" },
  "u8":{ "user":"Chris", "age":25, "country":"United States" },
  "u9":{ "user":"Louis", "age":31, "country":"Spain" },
  "u10":{ "user":"Emily", "age":38, "country":"Uraguay" },
  "u11":{ "user":"Shawn", "age":52, "country":"Chile" },
  "u12":{ "user":"Greg", "age":24, "country":"Romania" }
}

0 个答案:

没有答案