简体   繁体   English

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

[英]How to receive ,send and store a json array through ajax

I want to get a json array from ajax call and store it in a array . 我想从ajax调用中获取一个json数组并将其存储在数组中。 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 ? 我尝试了这段代码,但没有用。警报向我显示了字符串{“ value”:[1]},{“ value”:[2]} 。我需要将此字符串转换为JSON数组并存储在myData中.responseJSON是否有任何其他问题? 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 这是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'].']}'.','; } } ?> 

You're not returning the JSON array properly, because you don't have the [ ] around the array elements. 您没有正确返回JSON数组,因为数组元素周围没有[ ] You should just construct a PHP array and call json_encode on it. 您应该只构造一个PHP数组并对其调用json_encode

$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 提醒myData ,它应显示

{ values: [1, 2] }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM