我无法将PHP中的json数据转换为javascript JSON格式。当我使用responseText()函数时,我可以看到该数据是从PHP成功解析的。但是当我将ajax响应转换为JSON时,例如var json = JSON.parse(ajax.responseText)
,我看不到任何输出到屏幕的信息。我不介意jquery的答案,但我想在纯javascript中看到至少一个例子。
header('Content-Type: application/json');
if (isset($_POST["height"])) {
$height = preg_replace('/[^0-9]/', '.', $_POST['height']);
$width = preg_replace('/[^0-9]/', '.', $_POST['width']);
$areaInches = $height * $width;
$areaCM = $areaInches * 0.00064516;
$result = array(
'area_inches' => $areaInches,
'area_cm' => $areaCM
);
echo json_encode($result);
}
function sendData() {
var height, width;
height = parseFloat(document.getElementById('input_height').value);
width = parseFloat(document.getElementById('input_width').value);
console.log(height);
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = JSON.parse(ajax.responseText);
document.getElementById('jsondata1').innerHTML = json.area_inches + "ft^2";
document.getElementById('jsondata2').innerHTML = json.area_cm + "cm^2";
console.log(ajax.responseText);
} else {
console.log('error');
}
};
ajax.open("POST", "calculate_area.php", true);
ajax.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
ajax.send('height=' + height +
'&width=' + width
);
}
<h1>Calculate Area of Rectangle</h1>
<div class="wrapper">
<label>Height</label>
<input id="input_height" class="clear" type="text">
</div>
<div class="wrapper">
<label>Width</label>
<input id="input_width" class="clear" type="text">
</div>
<br>
<div class="wrapper">
<button onclick="sendData();">Calc. Area</button>
<input id="jsondata1" class="mt" type="text" readonly>
<input id="jsondata2" class="mt" type="text" readonly>
<div></div>
</div>