javascript - 如何使用 get 方法将 ajax 与 graphql 结合使用?

标签 javascript jquery ajax django graphql

我正在尝试遵循有关 django and graphql 的文档

https://www.techiediaries.com/django-graphql-tutorial/graphene/

我距离使用 graphql 进行测试仅完成了一半查看并提出我们的查询。

然后我停下来尝试做一些前端工作来使用ajax进行查询

正在阅读

https://blog.graph.cool/how-to-use-graphql-with-jquery-51786f0a59cb

尽管在该博客中,它使用 post 。我相信使用 get应该不会有太大的不同。

所以我尝试制作query然后将 JSON.stringify 转换为字符串他们将其传递到后端django但我不断收到错误

这是我的错误

XMLHttpRequest cannot load localhost:8000/graphql/?{"query":"query { allProducts {id sku title description } }"}. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

这是html+jquery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <button class="graphql-test">CLICK</button>
</body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
    <script>
        $(function(){
            $('.graphql-test').on('click', function(e){
                e.preventDefault();


                var query = "query { allProducts {id sku title description } }";

                $.ajax({
                    method: 'get',
                    url: 'localhost:8000/graphql/',
                    data: JSON.stringify({"query": query}),
                    contentType: 'application/json',
                    success: function(data){
                        console.log(data);
                    },
                    error: function(data){
                        console.log(data);
                    }

                })
            })
        });
    </script>
</html>

最佳答案

看来您需要更改 ajax 调用以包含完整的 URL。

改变

url: 'localhost:8000/graphql/'

url: 'http://localhost:8000/graphql/'

关于javascript - 如何使用 get 方法将 ajax 与 graphql 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46721015/

相关文章:

javascript - 应预加载哪些内容以及如何预加载?

jquery - 尝试加载 json 时 jqGrid 给出异常

php - 使用 php 和 ajax 的登录表单

javascript - 使用 Ajax 从特定 URL 加载数据

javascript - 通过 Chrome 扩展将 AJAX 注入(inject)网站

javascript - 基于 HTML 选择选项执行 Node.JS 查询

javascript - ng-if 花费 500 个观察者 - 性能

javascript 两个日期之间的时间

Javascript 重构 - 怎么做?

javascript - 滚动顶部,然后滚动底部,然后滚动顶部,然后滚动底部