使用MYSQL数据库数据加载Javascript数组 [英] Load Javascript array with MYSQL database data
问题描述
假设我有一个JavaScript数组"userName".我想从名为"user"的数据库表中加载它.
suppose i have an javascript array "userName".I want to load it from a database table named "user".
任何人都可以提供想法或示例代码帮助吗?
Can anyone help with idea or sample code?
谢谢
推荐答案
使用ajax和php作为中间体:
Use ajax and php as an intermediate :
-
定义一个空的JS数组:
Define an empty JS array :
var myarray = new Array();
使用ajax调用您的php脚本,javascript将评估PHP的输出(请注意,这使用原型库):
use ajax to call your php script, javascript will eval the output by PHP (note this uses prototype library):
new Ajax.Request('myfile.php', {
onSuccess : function(xmlHTTP) {
eval(mlHTTP.responseText);
}
});
编写您的PHP代码以获取数据并打印JS代码(它必须是有效的javscript!):
Write your PHP code to grab data and print JS code (it must be valid javscript !) :
$i=0; $q=mysql_query('select ..');
while($row=mysql_fetch_array($q)){
echo "myarray[".$i."]='".$row['data']."';";
$i++;
}
您可以检查您的Js数组是否包含数据:
You can check that your Js array contains data :
alert(myarray.length);
希望这会有所帮助.
这篇关于使用MYSQL数据库数据加载Javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!