【问题标题】:how to use ajax with graphql using get method?如何使用 get 方法将 ajax 与 graphql 一起使用?
【发布时间】:2018-03-25 01:33:04
【问题描述】:

我正在尝试关注有关 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>

【问题讨论】:

  • 我下面的回答解决了吗?
  • @MikeGorski 不走运:(

标签: javascript jquery ajax django graphql


【解决方案1】:

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

改变

url: 'localhost:8000/graphql/'

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

【讨论】:

  • 让我继续前进 :D 我犯了另一个愚蠢的错误,这就是为什么它不起作用
猜你喜欢
  • 2019-06-15
  • 2021-08-14
  • 2016-09-24
  • 2016-09-19
  • 1970-01-01
  • 2021-02-09
  • 2020-10-21
  • 2019-04-29
  • 2019-03-17
相关资源
最近更新 更多