本文介绍了如何发送带有变量的 GraphQL AJAX 查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 GraphQL 对 GitHub 进行 API 调用,我已经能够通过静态 graphQL 调用成功调用数据,但是我无法在调用中放置变量(var 条目)以便我可以更改基于用户在网络应用中提供的输入的调用.

I am trying to make an API call to GitHub using GraphQL, I have been able to successfully call data with a static graphQL call, however I am having trouble putting a variable (var entry) in my call so that I can change the call based on an input a user would provide in the web app.

我使用 AJAX 来传递授权令牌.此外,除非查询是 JSON 字符串化的(否则会得到 400 错误),否则调用将不起作用.

I am using AJAX to be able to pass the authorization token. Additionally, the call does not work unless the query is JSON stringified (gets 400 error otherwise).

JSON Stringify 似乎将变量 'superQuery' 的名称转换为字符串,而不是将 'superQuery' 的值转换为字符串.

The JSON Stringify seems to turn the name of the variable 'superQuery' into a string rather than turning the value of 'superQuery' into a string.

如何发送带有可根据用户输入更改的变量的 graphQL 查询?

How can I send a graphQL query with a variable that can change based on user input?

附言Web 开发的相对菜鸟,对于任何非常明显的错误表示歉意.

P.S. Relative noob to web development, apologies for any super obvious mistakes.

这是我目前所拥有的:

var entry = $('#entry').val()

  var superQuery = `{
    repository(name: entry, owner: "******") {
      pullRequests(last: 100) {
        nodes {
          state
          headRepository {
            owner {
             login
            }
           }
          }
         }
        }
       }`

.ajax({
  method: "POST",
  url: "https://api.github.com/graphql",
  contentType: "application/json",
  headers: {
    Authorization: "bearer **********************************"
  },
  data: JSON.stringify({
    query: superQuery
  })
})

推荐答案

对于任何有同样问题的人,以下是我最终运行时代码的样子:

For anyone with the same problem, here is what the code looked like when I finally got it to work:

      $('button').click(function() {
      event.preventDefault();
      var entry = $('#entry').val()
      console.log(entry);


      $.ajax({
          method: "POST",
          url: "https://api.github.com/graphql",
          contentType: "application/json",
          headers: {
            Authorization: "bearer ***********"
          },
          data: JSON.stringify({
            query: `query ($entry: String!) {repository(name: $entry,
            owner: "*******") { pullRequests(last: 100) {
              nodes {
                state
                headRepository {
                  owner {
                    login
                  }
                }
              }
            }
          }
        }`,
        variables: {
          "entry": $('#entry').val()
        }
      })
    })

这篇关于如何发送带有变量的 GraphQL AJAX 查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-23 05:25