从MySQL到JavaScript变量变量、MySQL、JavaScript

2023-09-10 20:41:48 作者:‰紙醉金迷ゞ

寻找这里简单的解决办法,我环顾四周,但似乎没有给我一个简单的解决方案。我想获得的数据从我的MySQL数据库,然后进入我的javascript变量。

Looking for a simple solution here, I have looked around but nothing seems to give me a simple solution. I want to get data FROM my mysql database and then into my javascript variables.

在我的的.js 文件 test.js 这两个变种项目命名,此文件被称为进入我的的.html 文件。

These two var items in my .js file named test.js and this file is called into my .html file.

var tag_name = 'example';
var client_id = '123456789';

在称为的.php 文件 call.php 我用这个方法(PDO)来获取所需的数据从的MySQL

In a .php file called call.php I use this method (PDO) to get the required data from MySQL:

$stmt = $db->query('SELECT * FROM data WHERE id=1');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$tag_name = $row['tag_name']; 
$client_id = $row['client_id'];
}

我想尝试并取得沿着这行的东西了的.js 文件 test.js - 这显然​​不会工作,但希望揭示了什么,我想实现一些轻:

I want to try and achieve something along the lines of this in the .js file test.js - this obviously wont work but hopefully sheds some light on what I am trying to achieve:

var tag_name = '<?php echo $tag_name ?>';
var client_id = '<?php echo $client_id ?>';

我能做到这一点使用阿贾克斯的方法?在我的研究,我读了我需要使用 JSON ?如果这个问题已经问过,请告诉我去后,是不是只是有人倾倒50+的code线。

Can I do this using an Ajax method? In my research I read that I need to use JSON? If the question has been asked before, please direct me to a post that is not just someone dumping 50+ lines of code.

推荐答案

在这里你去:

JavaScript的部分:

The javascript part:

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

call.php 文件:

$stmt = $db->query('SELECT * FROM data WHERE id=1');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$tag_name = $row['tag_name']; 
$client_id = $row['client_id'];
}
echo json_encode(array($tag_name,$client_id));