简体   繁体   English

使用javascript ajax接收数据并在html中显示

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

Here is my code: a js file named query.js that recieves an object array with database data:这是我的代码:一个名为 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();
}

and this is in a php file in the html body:这是在 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>

When i tested the JSQuery function directly in the html body, I was able to successfully update the paragaph 'txt' with the data, but now that I have moved it out to another file, including it in the html file, calling it from an onclick function, returning the object, and trying to display, it doesn't display anything.当我直接在 html 正文中测试 JSQuery function 时,我能够成功地用数据更新段落“txt”,但现在我已经将它移到另一个文件中,包括它在 ZFC35FZ30D5FC688 文件中调用它2C7A5E362 onclick function,返回 object,并尝试显示,它没有显示任何内容。 What am I doing wrong?我究竟做错了什么?

if you want to go to another url another you can use AJAX and in ajax you can also receive data in json form. 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