[英]AJAX & PHP -Retrieving more than one value
到此為止,假設我的PHP腳本返回一個帶有兩個值的數組,我將如何在javascript中解決它們?
<script type="text/javascript">
function ValidateCard(cardno)
{
if (cardno.length==0)
{
document.getElementById("txtprice").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)
{
document.getElementById("txtprice").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","coding/validation/validatecard.php?cardno="+cardno,true);
xmlhttp.send();
}
</script>
如您所見,返回的任何內容都將發送並顯示在div標簽中,我該如何區分數據?
謝謝
您可以使用json對其進行序列化,以便javascript可以讀取它。
因此,在php中json_encode($arr);
http://www.php.net/manual/en/function.json-encode.php
然后在javascript中。 您應該能夠執行類似jsarr [key]的操作來獲取值
<?php
$result = array('success'=>1, 'messgae'=>"the message you want to show");
echo json_encode($result);
?>
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
result = xmlhttp.responseText.evalJSON(true);
//you can use result as array to get the information you want to check
if (result['success']) {
document.getElementById("successs").innerHTML=result['message'];
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.