douquan1015 2015-08-27 02:03
浏览 82
已采纳

如何通过ajax接收,发送和存储json数组

I want to get a json array from ajax call and store it in a array . I tried this code but it doest not work .The alert shows me the string {"value":[1]},{"value":[2]} .I need this string to be converted in JSON array and stored in myData .Is there any problem about the responseJSON or any other thing ? Plz help

making a call

setInterval(function showUser(str) {
 str="1";
        if (window.XMLHttpRequest) {
            
            xmlhttp = new XMLHttpRequest();
        } else {
           
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
        
          
          var myData=(xmlhttp.responseJSON);
            
             window.alert(myData);
            
               
            
            }
        
        xmlhttp.open("GET","new.php?q="+str,true);
        xmlhttp.send();
        
}, 1000)

and this is the code for new.php

<?php


$conn =mysql_connect("localhost","root","") or die ("we couldn't connect!");
mysql_select_db("webauth");
$rs = mysql_query("SELECT * FROM test") or die(mysql_error());
 while($row = mysql_fetch_array($rs))
 {
        echo '"{values":['.$row['value'].']}'.',';
 }

}

?>

</div>
  • 写回答

1条回答 默认 最新

  • duanchu3376 2015-08-27 02:09
    关注

    You're not returning the JSON array properly, because you don't have the [ ] around the array elements. You should just construct a PHP array and call json_encode on it.

    $result = array('values' => array());
    while ($row = mysql_fetch_array($rs)) {
        $result['values'][] = $row['value'];
    }
    echo json_encode($result);
    

    When you alert myData, it should show

    { values: [1, 2] }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 nrf52810-c三个a 程序
  • ¥15 lego-loam跑出来的roll误差很大
  • ¥50 求一个半透明没有锯齿的圆角窗体的实现例子
  • ¥15 STM32cubeMX里的FreeRTOS无法释放内存
  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对