简体   繁体   中英

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:

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:

<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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM