使用JavaScript从Web服务获取JSON
当我单击HTML中的按钮以使用JavaScript时,会出现此错误使用JavaScript从Web服务获取JSON,javascript,json,ajax,Javascript,Json,Ajax,当我单击HTML中的按钮以使用JavaScript时,会出现此错误 myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) 这个JSON是我在访问时得到的 第三个参数表示请求是否异步。因此,通过查看您的代码,它应该是同步的。当我更改时,readyState==4和&status==200块中设置的readystatech
myapp.azurewebsites.net/:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
这个JSON是我在访问时得到的
第三个参数表示请求是否异步。因此,通过查看您的代码,它应该是同步的。当我更改时,
readyState==4和&status==200
块中设置的readystatechange处理程序中的ajaxRequest.responseText
的实际值是多少,我发现请求的resourceUse setRequestHeader()上不存在“Access Control Allow Origin”头,请将其添加到其中
function ajaxFunction() {
console.log("ajaxFunction()");
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Broken");
return false;
}
}
}
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var form = document.getElementById("myform");
var titleParagraph = document.getElementById("home_title");
titleParagraph.innerHTML = ajaxRequest.responseText;
form.style.display = "none";
}
}
var value1 = document.getElementById("field1").value;
var value2 = document.getElementById("field2").value;
var url = "https://webapp.azurewebsites.net/users/" + value1 + "/" + value2;
console.log(url);
// Call sign in web service
ajaxRequest.open("GET", url, true);
ajaxRequest.send(null);
var jsonResponse = JSON.parse(ajaxRequest.responseText);
console.log("RESPONSE:");
console.log(jsonResponse);
}
[{"ID":1,"UserName":"username","FirstName":"first","LastName":"last","email":"example@example.com"}]
ajaxRequest.open("GET", url, false);