簡體   English   中英

使用Javascript訪問Json對象

[英]Accessing Json object with Javascript

我需要幫助來理解這一點,我有一個簡單的JSON字符串,我的php腳本返回了該字符串: { "questions" : "question1"}

我訪問它的代碼是:

<script>

  var xhttp = new XMLHttpRequest();


 xhttp.onreadystatechange = function() {
 if (xhttp.readyState == 4 && xhttp.status == 200) {
     var jsond = JSON.parse(xhttp.responseText);
     document.getElementById("demo").innerHTML = jsond['questions'];
     document.getElementById("demo").innerHTML = jsond.questions;
    }
  }
  xhttp.open("GET", "make_exam.php", true);
  xhttp.send();
</script>

但是由於某些我所不知道的原因,它一直顯示不確定。 我已嘗試逐步了解所有內容,但似乎看不到我在做什么。 任何理解它的幫助或有關如何修復的建議都將受到贊賞。

我的PHP腳本在下面,我不認為故障在這里,但是我知道什么。

        $file= "my.json";

        $json = json_encode(file_get_contents($file));
        if(empty($json))
        {
            echo "nothing";
        }
        else
        {
            echo $json;
        }

大家好,這是完整的html文件

<!DOCTYPE html>
<html>
<head>
</head>

<body>
<button onclick="loadDoc()"> "Make Exam" </button>


 <p id="demo"> </p>

</body>



<script type="text/javascript">
function loadDoc() {


  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
    var jsond = JSON.parse(xhttp.responseText);
     alert(jsond);
    document.getElementById("demo").innerHTML = '<p>'+ jsond.questions +'</p>';
    }
  }
  xhttp.open("GET", "make_exam.php", true);
  xhttp.send();

  document.getElementById("demo").innerHTML = "hi";

}
</script>







</html>

您確定文件中存在關鍵的“問題”嗎? 這會返回什么

document.getElementById("demo").innerHTML = jsond

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM