您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在C#中,你可以使用AJAX技术结合GraphQL进行数据查询。这里是一个简单的示例,展示了如何在ASP.NET Core应用程序中实现这种结合。
首先,确保你已经安装了以下NuGet包:
创建一个GraphQL schema(模式)和对象类型。例如,我们创建一个简单的Person
类型:
public class PersonType : ObjectGraphType<Person>
{
public PersonType()
{
Field(x => x.Id);
Field(x => x.Name);
Field(x => x.Age);
}
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
ObjectGraphType
,并添加一个字段来获取所有人员信息:public class PersonQuery : ObjectGraphType
{
public PersonQuery()
{
Field<ListGraphType<PersonType>>("people", resolve: context =>
{
// 在这里返回你的数据源,例如从数据库获取数据
var people = new List<Person>
{
new Person { Id = 1, Name = "Alice", Age = 30 },
new Person { Id = 2, Name = "Bob", Age = 25 },
};
return people;
});
}
}
Startup.cs
中配置GraphQL端点:public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddNewtonsoftJson();
services.AddSingleton<ISchema, PersonSchema>();
services.AddGraphQL(options =>
{
options.EnableMetrics = true;
options.ExposeExceptions = true;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapGraphQL();
});
app.UseGraphQLPlayground(new GraphQLPlaygroundOptions());
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GraphQL AJAX Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>GraphQL AJAX Example</h1>
<button id="loadData">Load Data</button>
<ul id="peopleList"></ul>
<script>
$("#loadData").click(function () {
$.ajax({
url: "/graphql",
method: "POST",
contentType: "application/json",
data: JSON.stringify({
query: `
{
people {
id
name
age
}
}
`
}),
success: function (response) {
var people = response.data.people;
var list = $("#peopleList");
list.empty();
for (var i = 0; i< people.length; i++) {
list.append("<li>" + people[i].name + " (" + people[i].age + ")</li>");
}
},
error: function (error) {
console.log("Error: ", error);
}
});
});
</script>
</body>
</html>
现在,当你点击"Load Data"按钮时,AJAX请求将发送GraphQL查询,并在页面上显示查询到的人员信息。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。