1

我是这个网站的初学者和新手,我手头有我的项目,非常感谢一些帮助。

我正在使用第三方编写的 JQuery 插件。有3个javascript ieajs,b.js,c.js

a.js是 b.js 工作的框架

b.js包含一个表单构建器,它包含一个调用存储在c.js中的名为selectionOpt的 JSON 数组的函数

b.js中的函数如下

createChildren: function () {
        this._super();
        var self = this;

        this.comboselected = new DrawComboBox({
            styles: "comboselected",
            data: Draw.selectionOpt1,
            onChange:function () {
                self.comboselected = self.comboselected.value();
                    }       

   };
 });

c.js 中的 JSON 数组看起来像这样

Draw.selectionOpt1 = [
    {"Id": 1,"data": Blue,"label": "Blue","quantity": 100},
    {"Id": 2,"data": Red,"label": "Red","quantity": 100},
    {"Id": 3,"data": Green,"label": "Green","quantity": 100},
    {"Id": 4,"data": White,"label": "White","quantity": 100},
    ...etc..
    ...etc..
    }
    ];

我想将原始数据存储在数据库(MySQL)而不是 c.js 中,我目前正在为此苦苦挣扎。我有一个 PHP 脚本,即 api.php,如下所示

<?php 


 include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);

 $result = mysql_query("SELECT * FROM $tableName");          //query
$colouroptions = Array();                          //fetch result    

while( $obj = mysql_fetch_row($result) ) {  
 $colouroptions[] = $obj;  
}


 echo json_encode($colouroptions);  

?>

此脚本返回以下结果

[["1","Red","Red","100"],["2","Blue","Blue","100"],["3","Green","Green","100"], etc, etc.,...[etc, etc, etc, etc]]

Q1:如何从 MySQL 中获取数据并以期望的格式对其进行编码?

{"Id": 1,"data": Blue,"label": "Blue","quantity": 100},
{"Id": 2,"data": Red,"label": "Red","quantity": 100},
{"Id": 3,"data": Green,"label": "Green","quantity": 100},

etc etc etc

Q2:如何从b.js调用api.php生成的JSON数组?还是我需要先将其反馈给 c.js?怎么做到呢?

提前谢谢你。

4

3 回答 3

1

用于mysql_fetch_objectjson_encode以对象表示法而不是数组表示法生成 JSON。将数据加载到 JS 中的最简单方法是从 PHP 中回显它,如下所示:

<?php
echo '<script type="text/javascript">';
echo 'Draw.selectionOpt1 = ' . json_encode($colouroptions) . ';';
echo '</script>';
?>
于 2012-08-20T18:11:33.750 回答
0

如果您使用 jQuery,则 ajax 函数能够通过回调函数传递返回的结果。

$.ajax({
  url: 'ajax/test.php',
  dataType: 'json',
  success: function(data) {
    // here you can pass the results to another function
    createChildren(data);
  }
});


createChildren: function (passedData) {
        this._super();
        var self = this;

        this.comboselected = new DrawComboBox({
            styles: "comboselected",
            data: passedData,
            onChange:function () {
                self.comboselected = self.comboselected.value();
                    }       

   };
 });
于 2012-08-20T18:15:25.137 回答
0

尝试 mysql_fetch_assoc 而不是 mysql_fetch_row。它将创建一个关联数组,该数组将被解析为您想要的 json 格式。

(我不明白你的第二个问题)

于 2012-08-20T18:08:04.223 回答