簡體   English   中英

使用javascript ajax接收數據並在html中顯示

[英]Using javascript ajax to receive data and display it in html

這是我的代碼:一個名為 query.js 的 js 文件,它接收一個包含數據庫數據的 object 數組:

function JSQuery(query) {
  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var obj = JSON.parse(this.responseText);
      return obj;
    }
  };
  xhttp.open("GET", "php/query.php?q=" + query, true);
  xhttp.send();
}

這是在 html 正文中的 php 文件中:

<script src="js/query.js">
  </script>
  <script>
    function getQueryResults() {
      var obj = JSQuery('select * from User;');
      for (var i = 0; i < obj.length; i++) {
        document.getElementById("txt").innerHTML += obj[i].user_email + ' ' + obj[i].user_email + ' ' + obj[i].user_first + ' ' + obj[i].user_last + '<br>';
      }
    }
  </script>

  <center><button type="button" onclick="getQueryResults()">TEST</button></center>
  <center>
    <p id="txt"></p>
  </center>

當我直接在 html 正文中測試 JSQuery function 時,我能夠成功地用數據更新段落“txt”,但現在我已經將它移到另一個文件中,包括它在 ZFC35FZ30D5FC688 文件中調用它2C7A5E362 onclick function,返回 object,並嘗試顯示,它沒有顯示任何內容。 我究竟做錯了什么?

if you want to go to another url another you can use AJAX and in ajax you can also receive data in json form.

$("button").click(function(){
  $.ajax({url: "demo_test.txt", success: function(result){
    $("#div1").html(result);
  }});
}); 

暫無
暫無

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

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