xmlHttpRequest - 从php(数组)加载数据

时间:2013-10-17 04:27:14

标签: javascript php ajax arrays xmlhttprequest

我想在我的onchange中使用xmlhttprequest实现我的select option方法(在我的情况下, jquery禁止使用)。

这是我的select option代码:

<tr><td>
<form name="group" id="form1">
  <select name="group" id="group" onchange="member();">
    <option value="" disabled selected>Choose your group..</option>
      <?php foreach ($userGroups['data'] as $groups) {
         echo "<option value=\"".$groups['id']."\">".$groups['name']."</option>";
      }?>
  </select>
</form>
</td></tr>

<tr><td id="fetchmember">
   <!-- I HAVE NO IDEA WHAT CODE THAT I SHOULD WRITE HERE -->
</td></tr>

用于处理输入的PHP代码fetchmember.php

<?php
  include 'facebookauth.php';

    $groupId = $_GET['group'];
    $groupmember = $facebook->api('/'.$groupId.'/members');
    $membergroup = $groupmember['data'];

    foreach ($membergroup as $membergroups) {
      echo "<li>".$membergroups['name']."</li>";        
    }

?>

来自所选组之一的数组结果$membergroup):

Array ( [0] => 
   Array ( [name] => Oryza NurFa 
           [administrator] => 
           [id] => 1645819602 ) 
        [1] => 
   Array ( [name] => Muhammad Lathif Pambudi 
           [administrator] => 
           [id] => 100000251643877 ) 
        [2] => 
   Array ( [name] => Novantio Bangun 
           [administrator] => 
           [id] => 1152078197 ) 
        [3] => 
   Array ( [name] => Oliver Jordan 
           [administrator] => 
           [id] => 1065251285 ) 
        [4] => 
   Array ( [name] => Fauzan Sandy 
           [administrator] => 
           [id] => 1434833113 ) 
        [5] => 
   Array ( [name] => Arfan Fudyartanto D. N 
           [administrator] => 1 
           [id] => 1708602453 ) )

的Javascript

<script type="text/javascript">
  function member(str)
  {
    if (str==0)
    { 
      document.getElementById("fetchmember").innerHTML="";
      return;
    }
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        document.getElementById("fetchmember").innerHTML=xmlhttp.responseText;
      }
    }
  xmlhttp.open("GET","fetchmember.php?group="+str,true);
  xmlhttp.send();
  }
</script>

我得到的数据是一个数组。每次更改select选项(onchange)时,我都希望脚本加载fetchmember.php并自动打印$membergroups['name'](所选Facebook组中的成员姓名)。是否可以直接检索数组数据?我认为数组必须转换为XML/JSON。我不知道该怎么做。我知道我的代码中仍有许多不足之处,无论是php,html还是js。

请帮忙。任何建议将不胜感激。谢谢

2 个答案:

答案 0 :(得分:1)

试试这个:

I think you should convert array you return into JSON format.
And then after getting this in ajax response.
Finally convert it into regular format using javascript function and display into the div.

-

由于

答案 1 :(得分:0)

用jquery做吧。

jQuery("#fetchmember").empty();
jQuery.each(data, function(i, item) {
    jQuery("#fetchmember").append("someHTML");
});