我有一个表单,当我提交它时,我得到一个JSON文件,上面写着: {&#34;成功&#34;:false,&#34;消息&#34;:&#34;这是false&#34;} 如果表单为false且 {&#34;成功&#34;:true,&#34;消息&#34;:&#34;这是真的&#34;} < / strong>如果表单没问题。
我想要的是写一个 if语句并说明 JSON 文件是否为 true 以将我重定向到页面 else 重定向到其他地方。我想得到关键成功的价值......我想得到回来的字符串,对于密钥成功,它是真或假。这是下面的代码。 if语句无效。
Javascript代码:
function myFunction() {
var xhr = new XMLHttpRequest(),
method = "POST",
url = "that JSON file is";
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
var obj = JSON.parse(xhr.responseText);
if (obj.Success == "true"){
window.location = "http://www.google.com";
} else {
window.location = "http://yahoo.com";
}
};
xhr.send(data);
}
我缺少什么?希望有人可以提供帮助
感谢。
答案 0 :(得分:1)
这一行中唯一明显的错误是:
if (obj.Success == "true") {
obj.Success
属性已经包含true
或false
的布尔值,但强调不字符串值{{ 1}}。
因此,更正后的版本将为:
"true"
但是因为(在布尔逻辑中)if (obj.Success === true) {
与编写condition === true
一样,最简单的版本就是:
condition
虽然与问题无关,但请不要忘记在if (obj.Success) {
事件处理程序中检查HTTP请求是否实际成功。
答案 1 :(得分:-2)
尝试稍微改一下这个功能。显然你需要更改URL和对象数据端点,但这对我有用。
function getStuff(url) {
var xhttp, jsonData, parsedData;
// check that we have access to XMLHttpRequest
if(window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// get the data returned from the request...
jsonData = this.responseText;
// ...and parse it
parsedData = JSON.parse(jsonData);
// return the data here
// if the data you're returning is an object
// you need to know the endpoints
// for example, if there was a username,
// you might return parsedData.username
var success = parsedData.login;
// debug / test
if(success === 'RayanZenner') {
window.location = 'https://www.google.co.uk/';
} else {
window.location = 'https://uk.yahoo.com/';
}
var elementToShowStuffIn = document.getElementById('main');
elementToShowStuffIn.innerHTML = something;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
getStuff('https://api.github.com/users/RayanZenner');