How can I send a GraphQL AJAX query with a variable?

送分小仙女□ 提交于 2019-12-06 02:21:23

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()
        }
      })
    })

If I understand your question correctly, I believe you want to do the following (assuming entry is a string):

 var superQuery = `query repository($entry: String)
         repository(entry: $entry) {
            pullRequests(last: 100) {
               nodes {
                 state
                 headRepository {
                   owner {
                     login
                    } 
                  } 
                } 
             }
          }`

And then for your data:

data: JSON.stringify({
   query: superQuery,
   variables: { entry: entry }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!