簡體   English   中英

$ .get將json_encoded php數組返回給javascript

[英]$.get return json_encoded php array to javascript

我想從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);  

?>

編輯:

或者代替$ .get,我嘗試在PHP文件上執行此操作:

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>";

如果你的PHP返回一個JSON編碼的數據,你可以使用JSON.parse在你的Javascript中解析它:

function(returned_data) {
  returned_data = JSON.parse(returned_data);
}

returned_data現在將是一個JSON對象而不是原始字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM