将php数组移动到jquery中进行操作


Moving php array into jquery for manipulation

我有一个页面,通过PHP做一个SQL查询,并生成一个小数组。我希望在同一页面上的jquery能够利用数组,或者更具体地说,数组中的变量。

代码:

$result = mysql_query("SELECT characters_ID, name FROM characters where whichfamily = '$famID' && deathdate = '' && isfemale = '0' && $currentturn > borndate + 128",$db);
$rowcheck = mysql_num_rows($result);
//echo $rowcheck;
$suitablemembers = array();
$i = '0';
while ($row = mysql_fetch_assoc($result)){
    foreach ($row as $col => $val){
        if ($col == 'characters_ID') {
         $suitablemembers['idnum'][$i] = $val;
         }
         if ($col == 'name') {
            $suitablemembers['name'][$i] = $val; 
         }
         //$_SESSION['currentplayerCP'] = $val;
         //$_SESSION['currentplayerMaxCP'] = $val;
    }
    $i++;
   }
   print_r($suitablemembers);

print_r给出如下输出:

阵列([idnum] =>数组([0]=> 3[1]=> 10)[名字]=>数组([0]=> Orland [1] => Raguet))

下面是更多代码:

$('#displaysomedata').click(function() {
            //alert("Button clicked.");
            // somehow do a while or loop to display data from that array

        });  // end displaysomedata click function

我玩过JSON封装一些,但我不确定这是否是一个可行的解决方案。

如何将数据从php数组移动到jquery变量(在循环中)

JSON正是您需要的解决方案。PHP脚本将该数组编码为JSON,您可以在页面上回显它。

这里假设您不需要从PHP动态检索数据,而只是在页面加载时生成数据。如果你需要动态地检索它,你需要使用jQuery中的$.ajax()

$('#displaysomedata').click(function() {
        //alert("Button clicked.");
        // Use PHP to output the JSON-encoded array into a javascript variable
        var jsonobj = <?php echo json_encode($suitablemembers); ?>;
        // Now you can do whatever you need to with `jsonobj`
 });

注意:为了使其正常工作,上面的Javascript必须内联在PHP生成的同一页面上。如果它是通过<script src=>包含的,PHP不能修改它。

看一下PHP函数json_encode(),该页面的第一个示例是如何将数组编码为JSON。您可以使用getJSON从JQuery端加载它,如toopay所述。

//main.js

var system_array=[];
function get_array(){
    $.getJSON("/json/get_array.php", function(json) {
          system_array=json;
     });
}
//get_array.php

<?php
    $result_array=array(1,2,3,4,5);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($result_array);
    exit();
?>

将数据结果编码为JSON,并在jquery脚本中使用ajaxgetJSON检索。

编辑:

我想你需要一个例子来说明怎么做。

// At the last of your php script, uncomment this
// print_r($suitablemembers);
// and give a json instead
header('Content-Type: application/json');
echo json_encode($suitablemembers);

然后从你的html或js文件(或内联js),你可以执行ajax或使用get json简写

$('#displaysomedata').click(function() {
    //alert("Button clicked.");
    // Use PHP to output the JSON-encoded array into a javascript variable
    $.getJSON('path/to/above/script.php', function(data) {
       var items = [];
       $.each(data, function(key, val) {
       items.push(key + ':' + val);
       });
       alert(items.join(''));
    });
});