[英]$.get return json_encoded php array to javascript
I want to load a php array from a php file into a javascript array in a javascript file. 我想从php文件加载php数组到javascript文件中的javascript数组。
Originally, I was just doing var wordsArray = <?php echo json_encode($wordsArray) ?>;
本来,我只是在做
var wordsArray = <?php echo json_encode($wordsArray) ?>;
in a php file to get it, but now I've put all Javascript functions a .js
file, which can't run PHP. 在一个PHP文件中获取它,但现在我已经把所有Javascript函数都放在
.js
文件中,它无法运行PHP。 Is there a $.get
function that can return a php array? 是否有
$.get
函数可以返回php数组?
something like: 就像是:
JavaScript: Utilities.js file JavaScript:Utilities.js文件
$.get("php/Quests.php", {},
function(returned_data) {
var wordsArray = returned_data;
}
);
PHP: Quests.php file 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);
?>
EDIT: 编辑:
Or instead of the $.get, I tried doing this on the PHP file: 或者代替$ .get,我尝试在PHP文件上执行此操作:
echo "<script type='text/javascript'> var wordsArray =json_encode($wordsArray); </script>";
Then in JS do: 然后在JS做:
alert(wordsArray[1]);
Would something like this work? 会这样的吗?
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>";
If your PHP returns a JSON-encoded data, you can parse it in your Javascript using JSON.parse
: 如果你的PHP返回一个JSON编码的数据,你可以使用
JSON.parse
在你的Javascript中解析它:
function(returned_data) {
returned_data = JSON.parse(returned_data);
}
returned_data
will now be a JSON object instead of the original string. returned_data
现在将是一个JSON对象而不是原始字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.