简体   繁体   中英

Passing Variable From Ajax to Javascript

I know this question has been asked and possibly answered a few times but not in the exact context of which I require so to make sure I have full understanding, I wanted to ask with my specific scenario.

I require that when a HTML / Javascript page load, it triggers a server side call to query some information from the database. This information should then form an array on the server side which can then be passed to the client. From the client I should then be able to loop through the array and push them into the client side array (the reason I would loop and push is because in this context I may need to prefix some entries with strings before they are put into the array) which is then displayed to the user.

I have currently only seen examples where a div is targeted and replaced but not an array.

I have attempted a few different code attempts but sadly have had no luck (and cannot seem to fully understand how to pass values between client and server).

For what it's worth, I am fairly versed with other languages (C#, Python) so I am not a complete newby when it comes to this sort of stuff but this is a fairly new venture into Javascript / Ajax.

Generally easiest to use JavaScript Object Notation (JSON) when transporting data for use in JavaScript, hence json_encode:

<?php
//somearray.php
$arr = ["bar", "baz", "kaz"];
header('Content-Type: application/json');
echo json_encode($arr);

Then you just make you AJAX request using a library or whatever, decode the JSON and process as if you created it right there in the JavaScript:

<html>
<body>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://example.com/somearray.php";

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        var myArr = JSON.parse(this.responseText);
        prefix(myArr);
    }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

function prefix(arr) {
    var output = [];
    var i;
    for(i = 0; i < arr.length; i++) {
        output.push('foo ' + arr[i]);
    }
    console.log(output); //["foo bar", "foo baz", "foo kaz"]
}
</script>
</body>
</html>

(modified from http://www.w3schools.com/json/tryit.asp?filename=tryjson_http )

This information should then form an array on the server side which can then be passed to the client. From the client I should then be able to loop through the array and push them into the client side array

It might help to read up more on HTTP, how it is a "stateless" protocol and what an AJAX request is actually doing (hint; it's still stateless) because it sounds like you are not understanding where data exists on the server/client sides.

Okay, here is a small example on how you can do it. It is actually pretty simple when you are working with JSON. With json_encode() in PHP, you can easily convert arrays to JSON, receive them via AJAX and process the data with an each-loop.

Here is the code, which you can use for testings: HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>AJAX JSON Example</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
        <script>
            $(function(){
                $.getJSON('ajax.php',function(data){
                    $.each(data,function(index,value){
                        $('body').append('Name: ' + value.name + ' | City: ' + value.city + '<br />');
                    })
                });
            });
        </script>
    </head>

    <body>

    </body>

</html>

PHP:

<?
// I was too lazy to set up a DB for this example.
// You should know how to process database data in PHP
/*
$sql = "SELECT `id`,`name`,`city` FROM `useres`";
$result = $db->query($sql);
while($array = $db->assoc($result))
{
    $json['id']['name'] = $array['name'];
    $json['id']['city'] = $array['city'];
}
*/

// This part is only the example data which you should have received from the DB
$json[1]['name'] = 'Test Tester';
$json[1]['city'] = 'Test Village';

$json[2]['name'] = 'Claud Atlas';
$json[2]['city'] = 'Haven';

// echo the array as JSON
echo json_encode($json);
?>

Here you have an live example from the code above: https://work.walter-it.de/test/ajax/

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