您好,登錄后才能下訂單哦!
在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。