我想将php数组从php文件加载到javascript文件中的javascript数组中。
最初,我只是var wordsArray = <?php echo json_encode($wordsArray) ?>;
在php文件中进行操作,但是现在我将所有Javascript函数放到了一个.js
文件中,该文件无法运行PHP。有没有$.get
可以返回php数组的函数?
就像是:
JavaScript:Utilities.js文件
$.get("php/Quests.php", {},
function(returned_data) {
var wordsArray = returned_data;
}
);
PHP:Quests.php文件
<?php
include 'DbConnect.php';
$sql = $mysqli->query(
"SELECT t.*, v.*
FROM task t
INNER JOIN vocabtask vt ON (t.id = vt.taskid)
INNER JOIN vocab v ON (v.id = vt.vocabid)
WHERE vt.taskid = 1");
$wordsArray = array();
while ($row = $sql->fetch_assoc()) {
$wordsArray[$row['chinese']] = $row['english'];
}
mysqli_close($mysqli);
//return php array as json_encoded to js file through get function
echo json_encode($wordsArray);
?>
编辑:
或者,我尝试在PHP文件上执行以下操作,而不是使用$ .get:
echo "<script type='text/javascript'> var wordsArray =json_encode($wordsArray); </script>";
然后在JS中执行:
alert(wordsArray[1]);
这样的事情会起作用吗?
try this.
echo "<script type='text/javascript'> var wordsArray = " . json_encode($wordsArray) . ";
//this will output the contents of wordsArray into the console
console.dir(wordsArray);
// check the console. f12 or ctrl+shift+k
</script>";
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句