使用MYSQL数据库数据加载Javascript数组 [英] Load Javascript array with MYSQL database data

查看:77
本文介绍了使用MYSQL数据库数据加载Javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个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 :

  1. 定义一个空的JS数组:

  1. 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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆