简体   繁体   English

javascript-来自mysql数据库的变量值

[英]javascript - variable values from mysql database

In my site, I have a js file that performs some calculations. 在我的网站上,我有一个执行一些计算的js文件。 Currently I have my variables defined in another js file as global variables. 目前,我在另一个js文件中将变量定义为全局变量。

I would like to make them dynamical. 我想让它们充满活力。 By this I mean I want them to pull values from mysql database. 我的意思是我希望他们从mysql数据库中提取值。 I know that this is possible with ajax: 我知道使用ajax可以实现:

EXAMPLE: 例:

$.ajax({
    url: 'call.php',
    dataType: 'json'
}).done(function (data) {
    var tag_name = data[0];
    var client_id = data[1];
});

However, this is suitable for few values ( lets say 2 to 10). 但是,这适用于很少的值(假设2到10)。 In my case there are many variables (circa 200). 就我而言,有很多变量(大约200个)。 I think that it is not so good idea to make array of size 200 or more. 我认为制作大小为200或更大的数组不是一个好主意。

If I am wrong correct me please. 如果我错了,请纠正我。 Or if there is better solution to this, please inspire me :). 或者,如果有更好的解决方案,请给我启发:)。

Thank you 谢谢

If you have over 200 variables like you wrote here, I think you are organizing the code wrong. 如果您有200多个变量(如您在此处编写的那样),则我认为您在组织代码错误。 You should organize the code into objects that represent an object mapping of your database and call php functions according to your needs. 您应该将代码组织到代表数据库对象映射的对象中,并根据需要调用php函数。

In call.php use 在call.php中使用

print json_encode($data_array);
exit();

to encode your array. 编码数组。 You already have dataType: 'json' in your javascript $.ajax function. 您的javascript $ .ajax函数中已经有dataType:'json'。 You will NOT need to write var client_id = data[1]; 您无需编写var client_id = data [1]; Your data will be accesible through data.user_id, data.tag_name. 您的数据将通过data.user_id,data.tag_name访问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM