这是html文件
<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>
当我在我的浏览器中运行它时,请求没有被发送(我在后端的轨迹球中看不到任何东西) 如果在浏览器和 postman 中使用,该网址可以正常工作 this is the screenshot of postman request and response
后端在django中
这是我在控制台中得到的错误
var1 response = JSON.parse(xhttp.responseText);
错误:未捕获的语法错误:意外的标识符
最佳答案
我相信您的问题出在 xhttp.open
代码上。当您要求执行“GET”时,将末尾的 bool 值设置为 true 将意味着请求将异步执行。您应该将此变量设置为 false
,这意味着该方法在收到响应之前不会返回。
尝试改变
xhttp.open("GET","192.168.0.101:8000/students/",true);
到:
xhttp.open("GET","192.168.0.101:8000/students/",false);
这里有很好的资源:
希望对您有所帮助!
编辑
因为您似乎是服务器的所有者,您可以尝试在您的服务器上手动实现 CORS header ,或使用 JSONP (绕过 CORS)。这是 some info在 CORS 上并在 MDN 上实现。还有这个 nice source所以。祝你好运!
关于javascript - 我的 api 调用在 javascript 中不起作用,但在 postman 和浏览器中工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45087957/