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

问题描述

我正在尝试使用GraphQL对GitHub进行API调用,我已经能够通过静态graphQL调用成功调用数据,但是我在将变量(变量项)放入调用中时遇到麻烦,因此我可以进行更改基于用户将在网络应用中提供的输入进行呼叫.

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?

P.S.相对于Web开发的菜鸟,对于任何超级明显的错误表示歉意.

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

这是我到目前为止所拥有的:

Here is what I have so far:

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:24