0
使用AJAX將表單信息發送到php處理頁面。做一個var_dump可以發現數值是以「0」的形式出現的,即使輸入的數字不是。即使這些值指定爲「(int)」,PHP7也會返回「第20行/process_measurements.php中遇到的非數字值」。「AJAX請求中遇到的非數字值」。爲什麼沒有被捕獲的價值?
如果我明確地按照如下方式對它們進行了類型轉換,那麼PHP錯誤消失了,但是,var_dump顯示它們是以0形式進入的..不是輸入到表單中的值,因此計算結果爲0,不管輸入的值如何在形式中。
$length = (int)$length;
$width = (int)$width;
$height = (int)$height;
,因爲它顯示了「非數值遭遇」錯誤代碼:
<?php
function is_ajax_request() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
(int)$length = isset($_POST['length']) ? (int) $_POST['length'] : '';
(int)$width = isset($_POST['width']) ? (int) $_POST['width'] : '';
(int)$height = isset($_POST['height']) ? (int) $_POST['height'] : '';
var_dump($length, $width, $height);
$volume = $length * $width * $height;
if(is_ajax_request()) {
echo $volume;
} else {
exit;
}
?>
HTML and JS for further clarification:
<div id="measurements">
<p>Enter measurements below to determine the total volume.</p>
<form id="measurement-form" action="process_measurements.php" method="POST">
Length: <input type="text" name="length" /><br />
<br />
Width: <input type="text" name="width" /><br />
<br />
Height: <input type="text" name="height" /><br />
<br />
<input id="html-submit" type="submit" value="Submit" />
<input id="ajax-submit" type="button" value="Ajax Submit" />
</form>
</div>
<script>
var result_div = document.getElementById("result");
var volume = document.getElementById("volume");
function postResult(value) {
volume.innerHTML = value;
result_div.style.display = 'block';
}
function clearResult() {
volume.innerHTML = '';
result_div.style.display = 'none';
}
// omits textareas, select-options, checkboxes, radio buttons
function gatherFormData(form) {
var inputs = form.getElementsByTagName('input');
var array = [];
for (i = 0; i < inputs.length; i++) {
var inputNameValue = inputs[i].name + '=' + inputs[i].value;
array.push(inputNameValue);
}
return array.join('&');
}
function calculateMeasurements() {
clearResult();
var form = document.getElementById("measurement-form");
var action = form.getAttribute("action");
// gather form data
var form_data = gatherFormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', action, true);
// do not set content-type with FormData
//xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
console.log('Result: ' + result);
postResult(result);
}
};
xhr.send(form_data);
}
var button = document.getElementById("ajax-submit");
button.addEventListener("click", calculateMeasurements);
</script>
首先,如果您使用PHP 7.1,您可以執行'$ length = $ _POST ['length'] ?? '';'而不是使用'isset()' - 方法。但是,你的意思是'var_dump()'返回0嗎?如果是這樣,請提供'var_dump($ _ POST)'。 – junkfoodjunkie
它返回'array(0){}' – lookininward
如果是這樣,沒有什麼被髮送到'$ _POST'-顯示HTML。也許是JS。 – junkfoodjunkie