jQuery – 从数据库加载信息到不同的变量?

基本上我可以这样做,它打印出例如表中的一个字段,但我想将它们全部放到不同的表或其他什么,我将如何实现这一目标? 我把它作为我的保存/加载代码:

// Save/Load data. $('').ready(function() { if($.cookie('code')) { $.ajax({ type: "POST", url: "ajax/loadData.php", data: "code=" + $.cookie('code'), dataType: "json" success: function() { var json = $.parseJSON(); var coins = json.coins; var lvl = json.lvl; $('#test').html('lvl: ' + lvl + ' coins: ' + coins); } }); console.log('Loaded data from the database with the code ' + $.cookie('code')); } else { // Generate save&load-code var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"; var string_length = 64; var randomCode = ''; for(var i = 0; i < string_length; i++) { var num = Math.floor(Math.random() * chars.length); randomCode += chars.substring(num, num+1); } // Save code in cookies & database $.cookie('code', randomCode); console.log('Generated and saved code ' + $.cookie('code')); } }); 

请注意,我知道我还没有save-function / ajax,但我现在正在处理加载function。

这是我的loadData.php文件:

  

很简单,是的。 这将打印出属于特定用户的硬币数量。 这是表结构:

wohoo

我将如何将硬币和lvl字段加载到不同的变量或类似物中,以便我可以正确使用它们。

看起来Joroen帮助你解决了ajax方面,并希望你添加了他正在谈论的逗号。 php / mysqli部分可以这样写:

  

实际上,这段代码很可怕,因为您没有清理任何传入的数据并直接在SQL语句中使用它。 由于您已经知道它只允许使用A-Za-z0-9字符,因此您应该检查$ _GET [‘code’]的值,以确保它的使用安全。 我还强烈建议使用mysqli预处理语句,以避免一些有趣的东西,可能会发生污点输入。

这可能是一个糟糕的编程习惯,但这就是我将如何做到这一点。

 while($row = mysqli_fetch_array($query)) { $return = $row['coins'].",".$row['id'; //separate the send the values as a comma-separated string echo $return; 

}

js看起来像这样

 $('#coins').load('ajax/loadData.php?code=' + $.cookie('code')); //collect the values here var values = $(#coins).text(); //save the values in a srting var array_of_values = values.split(","); //split the string at a delimiter and save the values in an array 

请注意,如果查询返回多行,则不太可能