簡體   English   中英

使用JSON從JavaScript / jQuery中的PHP獲取數組,然后進行操作?

[英]Getting an array from PHP in JavaScript/jQuery using JSON, and manipulating it afterwards?

所以我陷入了一個相當棘手的問題。 我快要走了-太近了! -解決問題,但還不完全解決。 我看過很多示例,但沒有一個完全符合我的要求。

在php頁面myreqpdo.php上,我從MySQL表中恢復了一些數據行並將它們存儲在二維數組中。 在我的頁面index.php上,我需要通過JavaScript訪問此數組並在將其發送到需要填充的內容之前對其進行一些操作。

這是myreqpdo.php:

$locWanted = $_POST['searchTerm'];
echo json_encode(getVillesCPs($locWanted));

function getVillesCPs ($searchTerm) {
    // code to access DB here
    return $resultats;
}

我使用jQuery找到了這個示例 ,但是它是針對這樣一個實例的,其中一個人只想將列表直接插入代碼中,而無需任何進一步的操作:

<html>
<head>
        <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>

        <!-- this UL will be populated with the data from the php array -->
        <ul></ul>

        <script type='text/javascript'>
        $(document).ready(function(){
                /* call the php that has the php array which is json_encoded */
                $.getJSON('json_encoded_array.php', function(data) {
                        /* data will hold the php array as a javascript object */
                        $.each(data, function(key, val) {
                                $('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>');
                        });
                });

        });
        </script>

</body>
</html>

這對我不起作用,因為此功能是根據搜索參數觸發的功能。 我需要類似以下偽代碼的內容:

<script>
    var myArray = {code to recover PHP array};
    // manipulations for myArray here, using data to fill values of items on page
</script>

我一直認為答案就在我的眼底,但我確實沒有看到像我想要的例子那樣的例子! 有任何想法嗎?

您不需要jQuery在您的JavaScript代碼中從PHP插入數組,只需在需要的地方直接插入即可:

<script>
    var myArray = <?php echo json_encode(getVillesCPs($locWanted)); ?>;
    // manipulations for myArray here, using data to fill values of items on page
</script>

注意,在此代碼之前,必須在PHP代碼中為$locWanted var設置值, getVillesCPs將使用空參數調用其他getVillesCPs


編輯:由於您的getVillesCPs是在另一個PHP文件中定義的,因此在調用它之前將它包括在您的主頁中(假設您的主頁是一個PHP文件):

 <?php //including the PHP file containing the function include 'myreqpdo.php'; //setting a value for $locWanted, used then in the rest of the page $locWanted = 'Paris'; ?> <script> var myArray = <?php echo json_encode(getVillesCPs($locWanted)); ?>; // manipulations for myArray here, using data to fill values of items on page </script> 

並刪除myreqpdo.php前兩行代碼,您無需在調用函數之前echo任何內容。

暫無
暫無

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

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