![](/img/trans.png)
[英]Rails4 - How to receive and send JSON data securely through Ajax and store it?
[英]How to receive ,send and store a json array through ajax
我想從ajax調用中獲取一個json數組並將其存儲在數組中。 我嘗試了這段代碼,但沒有用。警報向我顯示了字符串{“ value”:[1]},{“ value”:[2]} 。我需要將此字符串轉換為JSON數組並存儲在myData中.responseJSON是否有任何其他問題? 請幫助
打電話
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)
這是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'].']}'.','; } } ?>
您沒有正確返回JSON數組,因為數組元素周圍沒有[ ]
。 您應該只構造一個PHP數組並對其調用json_encode
。
$result = array('values' => array());
while ($row = mysql_fetch_array($rs)) {
$result['values'][] = $row['value'];
}
echo json_encode($result);
提醒myData
,它應顯示
{ values: [1, 2] }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.