简体   繁体   中英

Jquery AJAX to retrieve PHP variable

I have a php script that makes my page load slowly because it fetches API data from another site and parses it so I want to make it load last. I'm reading AJAX is the way to go because it is asynchronous. Below is my AJAX code so far. All I want to do at the moment is have AJAX fetch a variable from PHP and display it but I can't get it to work. I think I'm really close though.

Here is the DIV I want it to load to and the script trigger.

<div id="results"></div>
<script type="text/javascript">ajax_lastcount();</script>

Here is the AJAX script

<script type="text/javascript">
function ajax_lastcount() {
var hr = new XMLHttpRequest();
hr.open("GET", "/viewcount.php", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
   if(hr.readyState == 4 && hr.status == 200) {
       var data = JSON.parse(hr.responseText);
       var results = document.getElementById("results");
       results.innerHTML = data;

       }
       }
     }
     hr.send(null);
     results.innerHTML = "requesting...";
}
</script>

Here is viewcount.php page

header("Content-type", "application/json");
$lastcount = "ten";
echo json_encode($lastcount);

Using jQuery this could be achieved by this code (called automatically after the page's DOM is loaded):

$(document).ready(function() {
    $.ajax({
        url: '/viewcount.php',
        type: 'get',
        dataType: 'json',
    })
    .success(function(data) {
        $('div#results').html(data);
    });
});

If you want to perform simplified GET or POST request, you can also call this instead:

$(document).ready(function() {
    $.get('/viewcount.php', {'optional_params_object':'value'})
    .success(function(data) {
        $('div#results').html(data);
    });
});

or

$(document).ready(function() {
    $.post('/viewcount.php', {'optional_params_object':'value'})
    .success(function(data) {
        $('div#results').html(data);
    });
});

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