Skip to content

Commit 1333636

Browse files
authored
feat(AjaxService): add ToJson parameter (#5441)
* refactor: 增加 toJson 参数 * refactor: 增加 ToJson 参数 * test: 增加单元测试 * test: 更新单元测试 * refactor: 更正单词拼写错误 * chore: bump version 9.3.1-beta34 * refactor: 精简代码
1 parent 69179e7 commit 1333636

File tree

4 files changed

+24
-18
lines changed

4 files changed

+24
-18
lines changed

src/BootstrapBlazor/BootstrapBlazor.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<Project Sdk="Microsoft.NET.Sdk.Razor">
22

33
<PropertyGroup>
4-
<Version>9.3.1-beta33</Version>
4+
<Version>9.3.1-beta34</Version>
55
</PropertyGroup>
66

77
<ItemGroup>

src/BootstrapBlazor/Components/Ajax/AjaxOption.cs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,10 @@ public class AjaxOption
2626
/// </summary>
2727
[NotNull]
2828
public string? Url { get; set; }
29+
30+
/// <summary>
31+
/// 获得/设置 是否获得序列化 Json 结果 参数 默认为 true
32+
/// </summary>
33+
[NotNull]
34+
public bool ToJson { get; set; }
2935
}

src/BootstrapBlazor/wwwroot/modules/ajax.js

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
method: 'POST',
44
url: null,
55
data: null,
6+
toJson: true,
67
...option
78
}
89

@@ -11,27 +12,24 @@
1112
return null
1213
}
1314

14-
const init = {
15-
method: option.method,
16-
headers: {
17-
'Content-Type': 'application/json'
18-
}
19-
}
20-
21-
if (option.method === 'POST' && option.data) {
22-
init.body = JSON.stringify(option.data)
23-
}
24-
25-
let json = null;
15+
let result = null;
2616
try {
27-
28-
const response = await fetch(option.url, init)
29-
json = await response.json()
17+
const { toJson, url, method, data } = option;
18+
result = await fetch(url, {
19+
method: method,
20+
headers: {
21+
'Content-Type': 'application/json'
22+
},
23+
body: method === 'POST' ? JSON.stringify(data) : null
24+
});
25+
if (toJson === true) {
26+
result = await result.json()
27+
}
3028
}
3129
catch (e) {
3230
console.info(e);
3331
}
34-
return json
32+
return result
3533
}
3634

3735
export function goto(url) {

test/UnitTest/Components/AjaxTest.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,12 @@ public async Task Ajax_Test()
1414
{
1515
Url = "/api/Login",
1616
Method = "POST",
17-
Data = new { UserName = "admin", Password = "1234567" }
17+
Data = new { UserName = "admin", Password = "1234567" },
18+
ToJson = false
1819
};
1920
Assert.Equal("/api/Login", option.Url);
2021
Assert.Equal("POST", option.Method);
22+
Assert.False(option.ToJson);
2123
Assert.NotNull(option.Data);
2224

2325
var service = Context.Services.GetRequiredService<AjaxService>();

0 commit comments

Comments
 (0)