我是这个网站的初学者和新手,我手头的项目很困难,真的很感激一些帮助。
我正在使用由第三方编写的JQuery插件。 有3个javascripts 即a.js,b.js,c.js
a.js 是b.js在
下工作的框架b.js 包含表单构建器,它包含一个函数,该函数调用存储在 c.js <中的名为 selectionOpt 的JSON数组/ p> 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?怎么做到呢?
先谢谢你。
答案 0 :(得分:1)
使用mysql_fetch_object
让json_encode
以对象表示法生成JSON而不是数组表示法。将数据加载到JS中的最简单方法是从PHP回显它:
<?php
echo '<script type="text/javascript">';
echo 'Draw.selectionOpt1 = ' . json_encode($colouroptions) . ';';
echo '</script>';
?>
答案 1 :(得分:0)
尝试使用mysql_fetch_assoc而不是mysql_fetch_row。 它将创建一个关联数组,该数组将被解析为您想要的json格式。
(我不明白你的第二个问题)
答案 2 :(得分: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();
}
};
});