【问题标题】:ajax call with jquery asp.net mvc使用 jquery asp.net mvc 进行 ajax 调用
【发布时间】:2014-08-16 00:50:11
【问题描述】:

我有一个按钮,类为“btn”,跨度为“ajaxtest”。当我单击按钮时,我想将文本“test”放在我的 span 标签中。这要在 ASP.NET MVC 中完成。

在视图中我有以下 ajax 调用:

<span id="ajaxtest"></span>
<input type="submit" class="btn" name="neverMind" value="Test BTN"/>

    <script>
    $(document).ready(function () {
        $(".btn").click(function () {
            $.ajax({
                method: "get",
                cache: false,
                url: "/MyController/MyAction",
                dataType: 'string',
                success: function (resp) {                       
                    $("#ajaxtest").html(resp);
                }
            });
        });
    });
    </script>

在 MyController 我有以下代码:

    public string MyAction()
    {
        return "test";
    }

我知道 Ajax 是如何工作的,我也知道 MVC 是如何工作的。我知道这个错误可能是因为我们期望控制器中有这样的东西:

public ActionResult MyAction()
    {
        if (Request.IsAjaxRequest())
        {
              //do something here
        }
        //do something else here
    }

但实际上这是我的问题。我不想用这个调用调用一些局部视图。我只想在我的跨度中返回一些字符串,我想知道这是否可以在不使用其他局部视图的情况下完成。

我想使用只返回字符串的简单函数。

【问题讨论】:

  • $("#ajaxtest").html(resp); 更改为$("#ajaxtest").text(resp);。此外,在成功函数中添加debugger; 以测试您从服务器返回的数据。

标签: ajax asp.net-mvc model-view-controller asp.net-ajax actionresult


【解决方案1】:

将 dataType: 'string' 更改为 dataType: 'text'

<script>
            $(document).ready(function () {
                $(".btn").click(function () {
                    $.ajax({
                        method: "get",
                        cache: false,
                        url: "/login/MyAction",
                        dataType: 'text',
                        success: function (resp) {
                            $("#ajaxtest").html(resp);
                        }
                    });
                });
            });
        </script>

我在本地检查它对我有用

【讨论】:

  • 这是我即将发布的答案并且是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-08
  • 2011-04-22
  • 1970-01-01
  • 2017-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多