我的api调用在javascript中不起作用,但在postman和浏览器中可以很好地工作
这是html文件我的api调用在javascript中不起作用,但在postman和浏览器中可以很好地工作,javascript,ajax,django,web,Javascript,Ajax,Django,Web,这是html文件 <html> <head> <title>"api call"</title> </head> <body> <div id="demo"> <script> function list() {
<html>
<head>
<title>"api call"</title>
</head>
<body>
<div id="demo">
<script>
function list() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET","192.168.0.101:8000/students/",true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Token ad4140b1caa4f98160bdc979a71a7215ae5972fe");
xhttp.send();
var1 response = JSON.parse(xhttp.responseText);
document.write(var1);
}
</script>
<button type="button" onclick="list()">click to get the list</button>
</div>
</body>
</html>
错误:未捕获的语法错误:意外的标识符我相信您的问题在于
xhttp。打开
代码。当您请求执行“GET”时,将末尾的布尔值设置为true将意味着请求将异步执行。您应该将此变量设置为false
,这意味着该方法在收到响应之前不会返回
试着改变
xhttp.open("GET","192.168.0.101:8000/students/",true);
致:
以下是好消息来源:
因为您似乎是服务器的所有者,所以可以尝试在服务器上手动实现CORS头,或者使用(绕过CORS)。下面是关于CORS和MDN的实现。还有这个等等。祝你好运 当您发出
请求时
将自动解析响应内容
改变
var1 response = JSON.parse(xhttp.responseText);
到
你收到了什么错误?@Alexandru IonutMihai我已经编辑过了,你可以在结尾看到我的答案。可能是@Alexandru IonutMihai的重复。我现在在控制台中得到了这个错误未捕获引用错误:列表未在HtmlButtoneElement.onclick(javascriptapi:21)中定义是的,这是一个很好的观点,但是不建议对ajax使用
async:false
(这是一种糟糕的做法),因为它会冻结窗口。请记住这一点!如果Kethan想要实现一个允许他保持请求异步的方法,对吗?@KethanChauhan您的授权应该类似于:“令牌ad4140b1caa4f98160bdc979a71a7215ae5972fe”
?这种格式似乎有点不合适。你在控制台中收到错误了吗?@cosnepenguin是的,我在控制台中收到一个错误,请看上面的edited@cosinepenguin查看我添加的屏幕截图捕获引用错误:列表未定义在HTMLButtonElement.onclick(javascriptapi:21)@Alexandru IonutMihail我现在得到这个错误
xhttp.open("GET","192.168.0.101:8000/students/",false);
var1 response = JSON.parse(xhttp.responseText);
var1 response = xhttp.responseText;