首页 > 解决方案 > Ajax 似乎在 ASP.NET Core 中不起作用

问题描述

我想在 ASP.NET Core 中使用 Ajax,但请求没有转到控制器。我使用 VS 2017 和 ASP.NET Core 2.1。

看法:

<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.7.0/d3.min.js"></script>
<script>
    $(document).ready(function () {
        $('#buttonDemo1').click(function () {

            $.ajax({
                type: 'GET',
                url: '/demo/demo1',
                success: function (result) {
                    $('#result1').html(result);
                }
            });
        });
    })
</script> 

<fieldset>
    <legend>
        <form>
            <input type="button" value="demo1" id="buttonDemo1" />
            <br />
            <span id="result1">

            </span>
        </form>
    </legend>
</fieldset>

控制器:

[Route("Demo1")]
public IActionResult Demo1()
{
    return new JsonResult("DEmo1");
}

启动.cs:

app.UseStaticFiles();
app.UseMvcWithDefaultRoute();

更新:我测试了这段代码,它在我的项目中工作:

     <script>
            function loadDoc() {
                var xhttp = new XMLHttpRequest();
                xhttp.onreadystatechange = function () {
                    if (this.readyState == 4 && this.status == 200) {
                        document.getElementById("demo").innerHTML = this.responseText;
                    }
                };
                xhttp.open("GET", "/Demo/demo1", true);
                xhttp.send();
            }
    </script>

感谢帮助

标签: c#ajaxasp.net-core

解决方案


相对 URL 可能存在问题:我将使用 c# 中的 URL Action Helper 生成 URL 在您看来:

<script>
$(document).ready(function () {

    var url = '@Url.Action("Demo1", "Demo")';

    $('#buttonDemo1').click(function () {

        $.ajax({
            type: 'GET',
            url: url,
            success: function (result) {
                $('#result1').html(result);
            }
        });
    });
});
</script>

推荐阅读