简体   繁体   中英

Get correctly formatted json from php to javascript?

I have a database with a tabled named options. In this table I have 3 fields

  1. id of type int autoincrement
  2. option_name of type varchar
  3. option_value of type varchar

Assume I have the following to records inserted already

  1. '1','homepage_title','Home'
  2. '2','index_page_title','Index Page'

I have a php script as follows

<?php
header("Access-Control-Allow-Origin: *");
//set timezone becuase some servers are jsut wrong
define('TIMEZONE', 'Europe/Athens');
date_default_timezone_set(TIMEZONE);

//Connect & Select Database
mysql_connect("somehost","simeuser","somepass") or die("could not connect server");
mysql_select_db("somedbdb") or die("could not connect database");

function getOptions(){
    $sqldata = mysql_query("SELECT * FROM `options`");
    $rows = array();
    while($r = mysql_fetch_array($sqldata)) {
        $rows[$r['option_name']][$r['option_value']][]=$r['option_value'];
    }

    echo json_encode($rows);
}
getOptions();
?>

It works because the script returns something like this

{"homepage_title":{"Home":["Home"]},"index_page_title":{"index page":["index page"]}}

I am sure the line that is incorrect is this one

$rows[$r['option_name']][$r['option_value']][]=$r['option_value'];

I just can't figure out what I need to fix. My intensions is to call javascript as follows

$.get("http://localhost/test-app/get_app_settings.php",function(data){
    var json = JSON.parse(data);
    console.log(JSON.stringify(json));
    alert("homepage title was "+json['homepage_title']);
    alert("index page title was "+json['index_page_title']);
});

I get Object object instead of Homepage which I expected in homepage_title and Index page which I expect in index_page_title.

I am sure it something really stupid but I just can see it.

What's your intention of doing this?

$rows[$r['option_name']][$r['option_value']][]=$r['option_value'];

Maybe you want just this?

$rows[$r['option_name']]=$r['option_value']; 

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