将ajax GET请求发送到ASP .NET Web API

时间:2017-11-17 13:10:41

标签: javascript jquery asp.net ajax

我使用以下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的genarated请求。

http://localhost:xxxxx/api/tudisp/Edit/?179

如何强制ajax不生成sign'?'通过id参数。

1 个答案:

答案 0 :(得分:4)

最简单的方法是更改​​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
    }
});

如果您想使用类似的东西,那么我强烈建议花一点时间让它变得更强大,但它就是您如何做您想做的事情的一个例子。