开发者

How to pass mysql table as an array to be used in javascript

I'm doing a simple javascript application. It involves several item开发者_如何学Pythons in different tables stored using MYSQL.

The user has to choose an item from a table. Based on his choice he can choose a second item from another table, then a third item from a third table based on his former choices, and continues on the same pattern.

I just have one simple problem that I don't know a simple method to import tables from MYSQL into javascript arrays!!

Any ideas of how to do that?!


I find the easiest way to send MySQL data to Javascript using PHP is as a JSON object using jQuery.

In PHP: connect to your db, do your query. Assuming you store your results in an array called $results, just do:

echo json_encode($results);

This will format the output as a JSON object.

This is the javascript side (using jquery) - note the GET var I'm passing as an example, in case you need that for the tablename or id or whatever:

$.getJSON( 'json.php', { some_get_var: 1 }, function(data){
    var i, total = data.length;
    for ( i = 0; i < total; ++i ) {
        // do whatever with your data, like populate a select.
        // your data would be like:
        // data[i].fieldname
    }
});


json_encode($arr)

The array you want to return, wrap it in the json_encode method. If you are using jQuery it will automatically convert it to an object in the success handler


You can't directly access your database from Javascript. You'll have to use PHP to render the JS code necessary for loading those arrays.

For that, you can use the json_encode function. You could also do it by ajax, that way, you can separate your php code from your JavaScript code and keep it organized.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜