简体   繁体   中英

Best way of transferring MySQL data to page javascript via PHP?

This question is a bit messy, so I'll try to stick to the basics of my problem. When users logs into my site, their site preferences are fetched from the database. The preferences could, for instance, represent a certain visual layout, customized by the user himself/herself. Let's say the user can choose to show or hide 3 "info"-boxes that are, by default, shown on the webpage. The preferences are stored like this in the db:

----------------------------------
| user_id | box_1 | box_2 | box3 |
----------------------------------
| 23      | true  | false | true |
----------------------------------

This data has to be fed into the javascript on the page, in order for the user to get their personal visual layout. So I would do something like this:

<head, title, jsscripts meta tags and what have you>
<script type="text/javascript">
<?php

//fetch data from db here
$array = fetchfunction();

echo 'preference_box_1 = '.$array['box_1'].';' // this would be set to true
echo 'preference_box_2 = '.$array['box_2'].';' // this would be set to false
echo 'preference_box_3 = '.$array['box_3'].';' // this would be set to true

?>
</script>

Is this the best solution to implement? Or is there a more elegant way? My concerns are also that this would be messy when a user has 100+ preferences.

EDIT: I'm sorry, I don't think I wrote my question clearly enough. I'm aware of PHP's JSON encoder, but the PHP code is not my concern here. What I'm wondering is if this is the best way to inject external data into javascript? Should it be done otherwise?

Personally I would consider transferring your data via JSON. It's lightweight and far more readable.

http://ditio.net/2008/07/17/php-json-and-javascript-usage/

You can use JSON encoder. PHP has one in-built , it is not flawless though, Zend Framework has better one (but it will use the in-built by default, you have to disable it).

I'd suggest using jQuery and PHPs function json_encode.

Once you read database values prepare result like so:

$result = array(
             'box_1' => $array['box_1'],
             'box_2' => $array['box_2'],
             'box_3' => $array['box_3'],
             'other_setting' => $array['other']
          );
print json_encode($result);

JavaScript loading code would look like this:

function load_settings(data) {
   if (data.box_1) {
      // do something if box is visible
   } 
}

$.ajax({
   url: your_site_url,
   dataType: 'json',
   success: load_settings
});

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