简体   繁体   中英

Separate each piece of data

If I'm retrieving more than 1 piece of data from mySql, how can I separate it in my js file. So I can use each piece of data in specific locations?

var hr = new XMLHttpRequest();
var pUrl = "../thephp.php";
hr.open("GET", pUrl, true);
hr.setRequestHeader("Contenet-type", "application/x-www-form-unlencoded");

hr.onreadystatechange = function(){
    if(hr.readyState == 4 && hr.status ==200){
        var return_data = hr.responseText;
    }
}
//ASSUMING 'logo1.jpg'  and  'Group Melago' are been sent via the php. how can I define them individually
var image = { 
    'back': { 'url':'img/logo1.jpg', 'img':null },
};
    var group ='Group Melago';

php

$query = $db->prepare('SELECT logoImage, groupName FROM sports WHERE eligible = ? ORDER BY RAND() LIMIT 1');
$array = array('N');
$query->execute($array);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($result);

PHP CODE:

$query = $db->prepare('SELECT logoImage, groupName FROM sports WHERE eligible = ? ORDER BY RAND() LIMIT 1');
$array = array('N');
$query->execute($array);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
var $jsonData=json_encode($result )
var_dump($jsonData);

JQUERY CODE:

$.ajax({
     url:"../thephp.php",
     dataType: "json",
     success: 
      function(jsonData) {
          //parse the json data returned from server 
      }
 });

Happy Coding :)

You can do this with jquery AJAX . Try the following code ,

JQUERY

<script>
$.ajax({
    type:'GET',
    url:'../thephp.php',
    dataType:'json',
    success: function(response){
        var image   =   response[0].logoImage,
            group   =   response[0].groupName;
    }
});
</script>

In thephp.php

$query = $db->prepare('SELECT logoImage, groupName FROM sports WHERE eligible = ? ORDER BY RAND() LIMIT 1');
$array = array('N');
$query->execute($array);
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($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