AJAX - PHP到Javascript多数组和拆分

时间:2014-04-28 19:41:58

标签: javascript ajax json

这里是JSON / AJAX的新手,但是尝试......

PHP页面似乎将[{“id”:“1”},{“id”:2}]返回到我的javascript。 如何将其转换为有用的内容,如html中的下拉列表?

代码:

<script>
function show(str) {
   if (str=="") {
    var ajaxDisplay=xmlhttp.responseText;
    var res=ajaxDisplay.split("#");
    document.getElementById("ajax1").innerHTML=res[1];
     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) {
    var ajaxDisplay=xmlhttp.responseText;
    var res=ajaxDisplay.split("#");
    document.getElementById("ajax1").innerHTML=res[0];
     }
   }
   xmlhttp.open("GET","get.php?q="+str,true);
   xmlhttp.send();
 }
</script>

<div id='ajax1'><b>ID dropdown will be listed here.</b></div>

1 个答案:

答案 0 :(得分:0)

我不确定你为什么要两次声明这些变量,但我认为如果你问我的想法,这可能会有所帮助。

function showUser(fo,to)
{

if (fo=="")
{
document.getElementById("show").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)
{
    var arr=xmlhttp.responseText.split(":||:");//I used this as the delimiter 
document.getElementById('show').innerHTML=arr[0];
     document.getElementById('show1').innerHTML=arr[1];
}
}
 xmlhttp.open("GET","some.php?q="+ fo + "&w=" + to,true);
 xmlhttp.send();
 }

并且php方面与正常情况不同,你需要这样的东西。

 if  (!$result=mysqli_query($con,$sql))
 {
 die('Could not get data: ' . mysqli_error($sql));
 }
 $test=mysqli_fetch_all($result,MYSQLI_ASSOC);//this was key to fetching the array properly for display
  $length=count($test);
  $half_length=$length/2;
 //echo $half_length."<br />";/used for testing
 $test12=array_chunk( $test,$half_length+.5,false);//here use true to preserve keys, worked both ways for me 
 $test5=$test12[0];
 $test6=$test12[1];
 while(list($key,$val)=each($test5))
 {
 echo "<p>".$val[$colunm_name]."<p/><br />";//Here you can put in the tags you want and will list your array in the format you want
  }
  echo ":||:";//Make sure the delimiter is out of the loop
 while(list($key2,$val2)=each($test6) )
 {
 echo "<p>".$val[$colunm_name]."<p/><br />";//Here you can put in the tags you want
 //echo "result_count_".count($test)."_-st<br/>";//used for testing 

我花了一段时间才得到这个,我希望它有所帮助。