GraphQL - JQuery集成

Web应用程序异步发送和检索数据(在后台). AJAX允许网站在不刷新页面的情况下将内容加载到屏幕上. jQuery为AJAX功能提供了几种方法,因此更容易使用AJAX.在本章中,我们将学习如何将GraphQL与jQuery集成.

考虑使用客户端服务器体系结构的应用程序.我们可以构建一个从GraphQL服务器请求数据的前端网页.该网页将使用jQuery向GraphQL服务器进行AJAX调用.

要将GraphQL与JQuery集成,让我们检查GraphiQL请求标头并理解请求参数.

启动 hello-world 应用程序(相关说明请参阅第6章).在GraphiQL窗口中键入graphql查询{greeting}.右键单击并检查或按下铬上的(ctrl + shift + I)以转到网络选项卡,如下所示 :

Chrome网络标签

从简单的 hello-world 示例中,我们可以理解 http方法使用的是 POST 的.现在在浏览器中,向下滚动到标题部分以查看请求有效负载.

点击查看代码后,将在chrome的请求有效负载部分中看到以下内容.

{"query":"{\n  greeting\n}","variables":null,"operationName":null}

另请注意请求URL, http://localhost:9000/graphql 应该从客户端应用程序调用.

插图

让我们了解如何使用逐步过程将GraphQL与JQuery集成./p>

设置服务器

我们将学习使用以下步骤设置服务器 :

第1步和第1步;下载并安装项目所需的依赖项

创建名为 jquery-server-app 的文件夹.从终端将目录更改为jquery-server-app.按照环境设置章节中说明的步骤3到5进行操作.

步骤2 : 创建模式

在项目文件夹 jquery-server-app 中添加schema.graphql文件并添加以下代码 :

type Query
{
   greeting: String
   sayHello(name:String!):String
}

该文件定义了两个查询问候 sayHello . sayHello查询接受字符串参数并返回另一个字符串. sayHello()函数的参数不为空.

步骤3 : 创建解析器

在项目文件夹中创建文件resolvers.js并添加以下代码 :

const Query =
{
   greeting: () => 'Hello GraphQL  From TutorialsPoint !!' ,
   sayHello:(root,args,context,info) =>  `Hi ${args.name} GraphQL server says Hello to you!!`
}
module.exports = {Query}

这里,问候语 sayHello 是两个解析器.在sayHello解析器中,传递给name参数的值可以通过args访问.要访问模块外部的解析器函数,必须使用 module.exports 导出Query对象.

步骤4 : 运行应用程序

创建server.js文件.请参阅环境设置章节中的步骤8.在终端中执行命令 npm start .服务器将在9000端口上启动并运行.在这里,我们使用GraphiQL作为客户端来测试应用程序.

打开浏览器并输入URL http://localhost:9000/graphiql .在编辑器中输入以下查询 :

{
   greeting,
   sayHello(name:"Mohtashim")
}

来自服务器的响应如下所示 :

{
   "data": {
      "greeting": "Hello GraphQL From TutorialsPoint !!",
      "sayHello": "Hi Mohtashim GraphQL server says Hello to you!!"
   }
}

设置客户端

因为我们已经设置好了服务器,现在我们将学习如何设置客户端.

步骤1和减号;在当前项目文件夹外创建一个新文件夹jquery-client-app

首先,我们将在项目文件夹外创建一个名为 jquery-client-app 的文件夹.

第2步和第2步;为jQuery Integration创建一个HTML页面index.html

我们将在jquery中创建一个客户端应用程序并调用这两个方法.以下是 index.html 文件的代码.当点击按钮 -   Greet SayHello 时, index.html 页面会向服务器发送请求.我们将使用$ .ajax()函数发出异步请求.

<!DOCTYPE html>
<html>
   <head>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script>
         $(document).ready(function() {

            $("#btnSayhello").click(function() {

               const name = $("#txtName").val();
               console.log(name);
               $("#SayhelloDiv").html('loading....');

               $.ajax({url: "http://localhost:9000/graphql",
                  contentType: "application/json",type:'POST',
                  data: JSON.stringify({ query:`{
                     sayHello(name:"${name}")}`
                  }),
                  success: function(result) {
                     console.log(JSON.stringify(result))
                     $("#SayhelloDiv").html("<h1>"+result.data.sayHello +"</h1>");
                  }
               });
            });
            
            $("#btnGreet").click(function() {
               $("#greetingDiv").html('loading....');
               //https://kannan-first-graphql-app.herokuapp.com/graphql
               $.ajax({url: "http://localhost:9000/graphql",
                  contentType: "application/json",
                  type:'POST',
                  data: JSON.stringify({
                     query:`{greeting}`
                  }),
                  success: function(result) {
                     $("#greetingDiv").html("<h1>"+result.data.greeting+"</h1>");
                  }
               });
            });
         });
      </script>
   </head>
   
   <body>
      <h1>Jquery Client </h1>

      <hr/>
      <section>
         <button id = "btnGreet">Greet</button>
         <br/> <br/>
         <div id = "greetingDiv"> </div>
      </section>
      
      <br/> <br/> <br/>
      <hr/>

      <section>
         Enter a name:<input id = "txtName" type = "text" value = "kannan"/>
         <button id = "btnSayhello">SayHello</button>
         <div id = "SayhelloDiv"> </div>
      </section>
   </body>
</html>

在浏览器中打开此文件,然后单击按钮以查看响应.输出将在下面给出 :

jQuery Integration的浏览器输出