0

I'm creating dynamic dropdown lists from values in my database. I'm querying the data, creating a php variable in this format:

$items = array(
   'red'=>'apples,firetrucks,blood',
   'yellow'=>'bus,pencil,duck'
);

I can then use the json_encode() function to encode.

{
  "red":"apples,firetrucks,blood",
  "yellow":"bus,pencil,duck",
}

I know the getJson is passed at file or a path like:

$.getJSON("jsondata/data.json", function(data) {

Can my json variable be passed to this function instead? The reason I want a variable to be passed, rather than a file is because my data can chance on a daily basis, ie:

$items = array(
   'red'=>'apples,firetrucks,bricks',
   'yellow'=>'bus,pencil,duck'
);
4

1 回答 1

0

您需要创建一个输出所需 JSON 的 PHP 文件;

/foo.php 中

echo json_encode(array(
    "red" => "apples,firetrucks,blood",
    "yellow" => "bus,pencil,duck",
));

...那么您的 JavaScript 应该发出 AJAX 请求来foo.php使用getJSON

$.getJSON("/foo.php", function (data) {
    alert(data.red); // shows "apples,firetrucks,blood
    alert(data.yellow); // you get the idea
});

...为您的对象数组创建值是如此诱人,但我拒绝了...不知何故

于 2013-04-30T20:16:24.810 回答