简体   繁体   中英

Getting JSON data from Javascript

I am currently working on a php/javascript project which retrieves information from a database and json encodes the data. It is supposed to show the values from the database inside a combo box on the web page.

In the PHP script that encodes the mysql data I have the following code:

$query = "SELECT pla_platformName as `platform` FROM platforms";

    $result = mysql_query($query);

    if ($result)
    {       
        while ($myrow = mysql_fetch_array($result))
        {
            $output[] = $myrow;                     
        }

        print json_encode($output);
        die();
    }

In the javascript code I have the following:

<script>
        $(document).ready(function()
        {
            getPlatforms();
            function getPlatforms()
            {
                $.post("phpHandler/get-platforms.php", function(json)
                    {
                        alert(json);    
                        alert(json.platform);
                    }
                );
            }
        });
    </script>

I have alert(json); which shows the entire json data which looks like the following:

[{"0":"hello","platform":"hello"},{"0":"android","platform":"world"}]

The next alert(json.platform) I am expecting it to show either hello or world or both but on this line it keeps on saying undefined. Why isn't this working and how do I get a specific platform, ie either hello, or world.

Thanks for any help you can provide.

Your platform member is defined on each item, you'll have to specify which array item you want the platform for. This should do the trick:

alert(json[0].platform);

I'm assuming that your json parameter actually holds a javascript object, and not simply a string. If it is a string, you should define contentType 'application/json' on your php page. (I'm not sure how you do that in php since I do .NET for server side myself.)

To test it quickly however, you can do a $.parseJSON(json) to get the object.

You need to first convert your JSON string into an object

var data = $.parseJSON(json);

In this case, the object returned is an array. Try

alert(data[0].platform);

You can skip the first step if you set the dataType option to json in your ajax call.

$.post("phpHandler/get-platforms.php", function(data) {
     alert(data[0].platform);
  }, 
  'json'
 );

See jQuery.post() documentation

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