【问题标题】:How to get .getJson to succeed如何让 .getJson 成功
【发布时间】:2012-08-24 00:41:00
【问题描述】:

我第一次尝试 Json,我不确定我在这里做错了什么,但我的成功回调永远被调用。我有一个名为 RIPreset 的下拉菜单,它在更改时调用以下代码。我知道 on change 部分工作正常。在我的 alert("popup1") 代码运行下面的代码中,我的代码后面也有一个断点,可以看到 getPreset 方法被调用并将字符串传递给结果,但我的 . getJSON 调用。即,alert("popup2") 永远不会被调用。我认为这意味着我没有从我的 JsonResult 传递有效数据,但我不确定我做错了什么。任何帮助,将不胜感激。

代码背后

    public JsonResult getPreset(int id)
    {
        RIPreset ripreset = db.RIPresets.Find(id);
        return Json(new { Description = ripreset.Description, LaborHours = ripreset.LaborHours, HourlyRate = ripreset.HourlyRate, Amount = ripreset.Amount });

    }

JQuery/Json

<script type="text/javascript">
$(document).ready(function () {
    $("#RIPreset").change(function () {

        var selection = $("#RIPreset").val();
        alert("popup1");
        $.getJSON('@Url.Action("getPreset")', { id: selection }, function (ripreset) {
            alert("popup2");
            $("#txtDescription").val(ripreset.Description);
            $("#txtHourlyRate").val(ripreset.HourlyRate);
            $("#txtLaborHours").val(ripreset.LaborHours);
            $("#txtAmount").val(ripreset.Amount);
        });
    });
});
</script> 

【问题讨论】:

  • 不确定这有多相关,但如果您在调试 ajax 请求时遇到问题,我建议您在浏览器中使用开发控制台进行调试 - 例如 firebug 或 chrome 开发工具

标签: jquery json asp.net-mvc-3


【解决方案1】:

出于安全原因,默认情况下禁用 GET 请求,请将您的操作更改为返回

public JsonResult getPreset(int id)
    {
        RIPreset ripreset = db.RIPresets.Find(id);
        return Json(new { Description = ripreset.Description, LaborHours = ripreset.LaborHours, HourlyRate = ripreset.HourlyRate, Amount = ripreset.Amount },
                    JsonRequestBehavior.AllowGet);

    }

【讨论】:

  • 成功了!谢谢一堆。顺便说一句,如果您不想使用 JSON 对象,为什么还要传递它?
  • 查看答案here
【解决方案2】:

只需像这样更改您的操作:

公共 JsonResult getPreset(int id) { RIPreset ripreset = db.RIPresets.Find(id); return Json(new { Description = ripreset.Description, LaborHours = ripreset.LaborHours, HourlyRate = ripreset.HourlyRate, Amount = ripreset.Amount }, JsonRequestBehavior.AllowGet); }

【讨论】:

    猜你喜欢
    • 2012-03-16
    • 1970-01-01
    • 2012-10-31
    • 2023-03-30
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多