这一定是一个非常简单的答案,但我看不出哪里错了。
只需在后面输入一个带有 C# 代码的测试 AJAX 请求。我无法让 c# 返回 true/false 语句,或者我无法让 AJAX 将其识别为 true/false。
[WebMethod]
public static bool testme(int testnumber)
{
if (testnumber < 12)
{
return true; }
else
{
return false;
}
}
Ajax :
<script>
$(document).ready(function () {
$('#test').click(function () {
$.ajax({
type: "post",
url: "WebForm1/testme",
data: { testnumber: 13 },
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
if (data) {
console.log("true");
}
else {
console.log("false");
}
},
Error:function(error){
console.log("error");
}
});
});
})
</script>
按钮:
<input type="button" id="test" value="click me"/>
console.log 显示为 true,即使我输入的数字大于 12,这应该从 c# 方法返回“false” bool 值。
最佳答案
您的 if(data)
检查正在检查真实性,data
将是一个对象,因此查看它的属性,您可以找到 C# 的结果。
如果您不熟悉 JS 真实性,请查找它以获得更好的描述:但是如果每个变量具有有效值,则它被认为是真实的,如果它为 null 或未定义(或 0 或 ''),那么它会不被认为是真实的,将无法通过 bool 检查。
关于javascript - 返回 Bool 到 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42773796/