我使用以下 ajax 脚本。
$.ajax({
dataType: 'json',
url: url,
data: tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
Web API 中方法前的属性 Route。
[Route("api/tudisp/Edit/{tuDispId}")]
public IHttpActionResult Edit(int tuDispId)
{
}
ajax 生成的请求。
http://localhost:xxxxx/api/tudisp/Edit/?179
如何强制ajax不生成符号'?'通过 id 参数。
最佳答案
最简单的方法是更改 Ajax 选项的 url 属性...
$.ajax({
dataType: 'json',
url: "http://localhost:xxxxx/api/tudisp/Edit/" + tuDispId,
type: "GET",
success: function (data) {
bindData(data);
$("#alert-placeholder").empty();
$('#alert-placeholder').removeClass('alert alert-danger');
},
error: function (xhr, textStatus, errorThrown) {
$('#alert-placeholder').addClass('alert alert-danger');
$('#alert-placeholder').html(errorThrown);
}
});
GET 参数会作为查询字符串自动附加到 Url,如果这是您的应用程序所期望的,这很好,但当您按原样使用路由时就不行了。
但是,如果您想修改现有的 Ajax 请求,您可以使用预过滤。此示例修改了 ajax 调用的 Url,将 {variable}
替换为数据对象中的给定值...
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.data = ""; // this removes the querystring
for (key in originalOptions.data) {
options.url = options.url.replace("{" + key + "}", originalOptions.data[key]);
}
});
$.ajax({
url: "http://localhost:xxxxx/api/tudisp/Edit/{tuDispId}",
data: {
"tuDispId": 179
}
});
如果您想使用类似的东西,那么我强烈建议您花点时间让它变得更健壮,但这是您如何做您想做的事的一个例子。
关于javascript - 向 ASP .NET Web API 发送 ajax GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47351440/