我使用了以下代码:
let response = await fetch("/LostEnergyCalculation/GetGridAndPieChartsData");
let data = await response.json();
没有参数,它工作正常,但如何使用参数?
答案 0 :(得分:3)
如果您需要获取POST
数据,则可以传递body
请求...
下面的示例在请求中传递表单样式数据,并使用接口返回类型化数据。
interface MyApiData {
name: string;
}
class Example {
async getData(foo: string, bar: string) {
let response = await fetch(
'/LostEnergyCalculation/GetGridAndPieChartsData',
{
method: 'post',
headers:new Headers({
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
}),
body: `foo=${foo}&bar=${bar}`
});
let data: MyApiData = await response.json();
return data;
}
}
const example = new Example();
example.getData('foovalue', 'barvalue').then((data) => {
alert(data.name);
});
答案 1 :(得分:0)
我的方法(事件处理程序)如下所示:
async onFieldSelectionChanged() {
const selectedOilField = $("#OilFieldsList").dxSelectBox("instance");
this.oilFieldId = selectedOilField.option("value");
if (this.oilFieldId === null) {
selectedOilField.option("value", 1);
this.oilFieldId = 1;
}
if (this.initialLoad) {
const startDateBox = $("#StartDate").dxDateBox("instance");
this.startDate = startDateBox.option("value").toISOString();
const endDateBox = $("#EndDate").dxDateBox("instance");
this.endDate = endDateBox.option("value").toISOString();
const periodGroup = $("#DateTimePeriod").dxRadioGroup("instance");
this.period = periodGroup.option("value");
//$.ajax({
// type: "POST",
// url: "/LossEnergyCalculation/GetGridAndPieChartsData",
// data: { oilFieldId: this.oilFieldId, periodGroup: this.period, startDate: this.startDate, endDate: this.endDate }
//}).done(data => {
// this.showDataGrid(data);
// this.showRealLossDonutChart(data);
// this.showNormativeLossDonutChart(data);
// this.initialLoad = false;
//}).fail(function (jqXHR, textStatus, errorThrown) {
// console.log("jqXHR: " + jqXHR.responseText);
// console.log("jqXHR status: " + jqXHR.status);
// console.log("textStatus: " + textStatus);
// console.log("errorThrown: " + errorThrown);
//});
const response = await fetch("/LossEnergyCalculation/GetGridAndPieChartsData",
{
method: "post",
headers: new Headers({
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
}),
body: "oilFieldId=${this.oilFieldId}&periodGroup=${this.period}&startDate=${this.startDate}&endDate=${this.endDate}"
});
const data = await response.json();
} else {
return;
}
}
调用fetch方法时失败,出现错误,您可以查看附加的屏幕截图。
顺便说一句,评论的ajax调用工作正常。
答案 2 :(得分:0)
我发现这种方式可以让它发挥作用:
let queryString = [
`oilFieldId=${this.oilFieldId}`,
`periodGroup=${this.period}`,
`startDate=${this.startDate}`,
`endDate=${this.endDate}`
].join('&');
const request = new Request(`/LossEnergyCalculation/GetGridAndPieChartsData?${queryString}`,
{
method: "POST"
});
const data = await fetch(request).then(response => response.json());