简单的getJSON不起作用

时间:2010-04-30 15:13:35

标签: c# javascript jquery asp.net-mvc

JSON功能(索引)不会触发。有任何想法吗?

<script type="text/javascript">
    $(document).ready(function() {
        alert("This alert is displayed :(");
        $("form[action$='GetQuote']").submit(function() {                
            $.getJSON($(this).attr("action"), $(this).serialize(), function(Result) {
                alert("This alert is not shown :(");
                $("#name").html(Result.name);
                $("#address").html(Result.address);
            });   
            return false;
        });
    });    
</script>

控制器...

    public JsonResult GetQuote(string dataName)
    {
        if (dataName != "" || dataName != null)
            return new JsonResult { Data = new Result { name = "Hello", address = "World" } };
        else
            return null;
    }

2 个答案:

答案 0 :(得分:2)

如果在默认情况下尝试使用HTTP GET执行此操作,ASP.NET MVC 2.0将引发错误。您可以将其设为POST或按照本文中的建议添加指令:

http://mhinze.com/json-hijacking-in-asp-net-mvc-2/

是: 返回Json(data,JsonRequestBehavior.AllowGet);

答案 1 :(得分:0)

首先,您可能应该使用$.ajax函数,并指定“POST”来发布您的dataName。

其次,您可能需要阻止发生默认事件:

$("form[action$='GetQuote']").submit(function(event) {
    if (event.preventDefault) // Older I.E. uses an old DOM model, which dosen't have this event
       event.preventDefault();

    $.ajax(...) // Do your ajax call
    return false; // Once again, for I.E.
});

提交事件可能会覆盖与jQuery绑定的onSubmit