我有以下HTML文件:
以下是代码:
<html>
<head>
<script>
function showCardInfo() {
var xmlhttp;
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("output").innerHTML = xmlhttp.responseText;
}
}
if (document.getElementById("transFlag").checked) {
xmlhttp.open("GET", "getCardInfo.php?id=" + document.getElementById("cardNo").value + "&transactions=true", true);
} else {
xmlhttp.open("GET", "getCardInfo.php?id=" + document.getElementById("cardNo").value, true);
}
}
</script>
</head>
<body>
<form style="font-family:verdana; font-size: 10pt">
<p>
Card number:
<input type="text" id="cardNo" />
<input type="checkbox" id="transFlag" checked="checked" />Include transactions
</p>
<p>
From:
<input type="date" id="fromdate" />To:
<input type="date" id="todate" />
<button type="button" style="width: 100px; height: 20px;" onclick="showCardInfo()">Enter</button>
</p>
</form>
</br>
<div id="output">
</div>
</body>
</html>
JSON格式是这样的:
{
"id": "123",
"createdate": "2013-07-30 21:11:19",
"balance": "10000",
"expirationdate": "2013-09-30 23:59:59",
"status": "active",
"createdby": null,
"signature": null
}
答案 0 :(得分:1)
在onreadystatechange
处理程序中,将json重新放入变量中。并处理数据以构造一个表并将表放在div中。
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var out = JSON.parse(xmlhttp.responseText);
var html = "<table><tr><td>id</td><td>createdDate</td><td>Balance</td></tr>";
html += "<tr><td>" + out.id + "</td><td>" + out.createddate + "</td><td>" + out.balance + "</td></tr></table>";
var content = document.getElementById('output');
content.innerHTML = html;
}
}
我只包含你的json对象的3个属性,我猜你将能够处理这个例子中的其余部分。
答案 1 :(得分:0)
您需要修改您的js代码
<script>
function showCardInfo()
{
var xmlhttp;
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("output").innerHTML=xmlhttp.responseText;
}
}
if (document.getElementById("transFlag").checked)
{
xmlhttp.open("GET","getCardInfo.php?id="+document.getElementById("cardNo").value+"&transactions=true",true);
xmlhttp.open("GET", "test.txt",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
}
xmlhttp.send(null)
}
else
{
xmlhttp.open("GET","getCardInfo.php?id="+document.getElementById("cardNo").value,true);
xmlhttp.open("GET", "test.txt",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
}
xmlhttp.send(null)
}
}
</script>