【问题标题】:my api call doesnot work in javascript but works fine with in postman and browser我的 api 调用在 javascript 中不起作用,但在邮递员和浏览器中可以正常工作
【发布时间】:2017-12-18 16:03:09
【问题描述】:

这是 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>

当我在浏览器中运行时,请求未发送(我在后端的跟踪球中看不到任何内容) 如果在浏览器和邮递员中使用,该 url 可以正常工作 this is the screenshot of postman request and response

后端在 django 中

这是我在控制台中遇到的错误

var1 response = JSON.parse(xhttp.responseText);

错误:未捕获的语法错误:意外的标识符

【问题讨论】:

  • 您收到什么错误?
  • @Alexandru-IonutMihai 我已经编辑了,你可以在最后看到
  • 看看我的回答。
  • @Alexandru-IonutMihai 我现在在控制台中收到此错误 Uncaught ReferenceError: list is not defined at HTMLButtonElement.onclick (javascriptapi:21)

标签: javascript ajax django web


【解决方案1】:

我相信您的问题出在xhttp.open 代码上。当您要求执行“GET”时,将最后的布尔值设置为 true 将意味着请求将异步执行。您应该将此变量设置为false,这意味着该方法在收到响应之前不会返回。

尝试改变

xhttp.open("GET","192.168.0.101:8000/students/",true);

到:

xhttp.open("GET","192.168.0.101:8000/students/",false);

这里有很好的来源:

希望对你有帮助!

编辑

由于您似乎是服务器的所有者,您可以尝试在您的服务器上手动实现 CORS 标头,或使用 JSONP(绕过 CORS)。这是 CORS 上的 some info 并在 MDN 上实现。 SO上还有这个nice source。祝你好运!

【讨论】:

  • 是的,这是一个好点,但不建议将async:false 用于ajax(这是一种不好的做法),因为它会冻结窗口。
  • 请记住这一点!如果 Kethan 想要实现一个 ajax promise,这将允许他保持请求异步,对吧?
  • @KethanChauhan 您的授权是否应该类似于:"Token ad4140b1caa4f98160bdc979a71a7215ae5972fe"?这种格式似乎有点不对劲。您是否在控制台中收到错误消息?
  • @cosinepenguin 是的,我在控制台中遇到错误,请参阅上面我已编辑
  • @cosinepenguin 查看我添加的截图
【解决方案2】:

当您创建request 时,响应的内容将被自动解析。

改变

var1 response = JSON.parse(xhttp.responseText);

var1 response = xhttp.responseText;

【讨论】:

  • Uncaught ReferenceError: list is not defined at HTMLButtonElement.onclick (javascriptapi:21) @Alexandru-IonutMihail 我现在收到此错误
猜你喜欢
  • 2019-10-02
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 2020-07-10
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
相关资源
最近更新 更多