gpt4 book ai didi

javascript - 基于发布值的 XMLHttpRequest 响应状态

转载 作者:行者123 更新时间:2023-12-03 11:46:19 24 4
gpt4 key购买 nike

我的 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 上返回自定义消息。

如果POSTed的值小于数据库中的值,我希望它给出“输入有效数字”或类似的内容。

我对 XMLHttpRequest 很陌生。我不知道如何实现这一目标。任何帮助将不胜感激。

最佳答案

您是否考虑过:而不是 statusDisplay.innerHTML = 'Saved!';:

statusDisplay.innerHTML = xhr.responseText;

如果你这样做,那么你的 statusDisplay 将等于你的 post.php 回显的内容。

例如,在 post.php 中

<?php

//handling $_POST['clientId'] ... etc

if (error)
echo "Enter Valid Number";
else
echo "Saved!";

关于javascript - 基于发布值的 XMLHttpRequest 响应状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26031576/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com