Return WebMethod 响应 & 使用 If 语句根据响应提醒用户
Return WebMethod Response & Use If Statement To Alert User Based On Response
我试图包含一个 if 语句来分析 webmethod 响应是真还是假。我只想提醒用户,如果响应为真,则 post 成功;如果响应为假,则 post 不成功。
我可以使用 xhttp.responseText 获得响应,但我不知道如何将其构建到下面我的 javascript 中的 if 语句中:
//JavaScript that Posts to WebMethod
<script>
function createNewComment() {
var xhttp = new XMLHttpRequest();
var url = "http://localhost:57766/PALWebService.asmx/insertComment"
var a = document.getElementsByName("existingguid")[0].value;
var b = document.getElementsByName("newcomment")[0].value;
var c = 'existingguid=' + a + '&newcomment=' + b;
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.send(c);
}
</script>
我明白了。在检查 readyState 为 4 且状态为 200 后,我简单地嵌套了另一个 if 语句来检查来自 XMLHttpRequest 的 responseText,它是 true 我调用了另一个函数,如果它是 false 我通知用户 post 在 webmethod 上失败。它可能并不完美,但它可以满足我的需要。
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (xhttp.responseText = true) {
addComment(b, today, userName);
}
else {
document.getElementsByName("newcomment")[0].value = '';
$("#commentLabel").html("Your comment was not saved in the database. Please try again or contact system admin.");
}
}
};
我试图包含一个 if 语句来分析 webmethod 响应是真还是假。我只想提醒用户,如果响应为真,则 post 成功;如果响应为假,则 post 不成功。
我可以使用 xhttp.responseText 获得响应,但我不知道如何将其构建到下面我的 javascript 中的 if 语句中:
//JavaScript that Posts to WebMethod
<script>
function createNewComment() {
var xhttp = new XMLHttpRequest();
var url = "http://localhost:57766/PALWebService.asmx/insertComment"
var a = document.getElementsByName("existingguid")[0].value;
var b = document.getElementsByName("newcomment")[0].value;
var c = 'existingguid=' + a + '&newcomment=' + b;
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.send(c);
}
</script>
我明白了。在检查 readyState 为 4 且状态为 200 后,我简单地嵌套了另一个 if 语句来检查来自 XMLHttpRequest 的 responseText,它是 true 我调用了另一个函数,如果它是 false 我通知用户 post 在 webmethod 上失败。它可能并不完美,但它可以满足我的需要。
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (xhttp.responseText = true) {
addComment(b, today, userName);
}
else {
document.getElementsByName("newcomment")[0].value = '';
$("#commentLabel").html("Your comment was not saved in the database. Please try again or contact system admin.");
}
}
};