我有一个JavaScript函数,它执行XMLHttpRequest。这是我的密码。
function addbilldetails() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = 'http://example.com/post.php';
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed
var clientId = "clientid",
submittype = "a",
name = encodeURIComponent(document.getElementById('name').value),
billno = encodeURIComponent(document.getElementById('billno').value),
mobileno = encodeURIComponent(document.getElementById('mobileno').value),
phoneno = encodeURIComponent(document.getElementById('phoneno').value),
netAmount = encodeURIComponent(document.getElementById('netAmount').value);
var params = 'clientId=' + clientId +
'&billno=' + billno +
'&mobileno=' + mobileno +
'&phoneno=' + phoneno +
'&netAmount=' + netAmount +
'&type=' + submittype +
'&name=' + name;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
document.getElementById('save').disabled = false;
// window.setTimeout(window.close, 1000);
} else {
// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
document.getElementById('save').disabled = true;
}
现在,上面的代码工作得很好,并在POST
上返回200
。但我希望它根据发布的值在UI上返回自定义消息。
如果值POST
ed小于数据库中的值,我希望它给出"输入有效数字"或类似的内容。
我是XMLHttpRequest
的新手。我不知道如何做到这一点。如有任何帮助,我们将不胜感激。
您是否考虑过statusDisplay.innerHTML = 'Saved!';
:
statusDisplay.innerHTML = xhr.responseText;
如果你这样做,那么你的状态显示将等于你的post.php
回声。
例如,在post.php 中
<?php
//handling $_POST['clientId'] ... etc
if (error)
echo "Enter Valid Number";
else
echo "Saved!";