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'].']}'.','; } } ?>
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] }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.