开发者

jsonresult does not come back?

trying to display a success message from the controller?

  [HttpPost]
    public JsonResult SuccesMsg()
    {
        return Json(new { Success = true });
    }

jquery:

        $("#but").click(function () {
            $.ajax({
                url: "/Home/SuccesMsg",
                type: 'POST',
                data: "",
                success: function (result) {
                    if (resultJson['Success'] == true) {
                        alert('suc开发者_开发知识库cess');
                    }

                    else
                    { alert('no'); }
                },
                error: function (err) { alert('error') }
            });
        });


Add dataType: "json" to your $.ajax call or use the shorthand: $.getJSON.

Also check that your controller handles the response returns in state http 200 (OK).

For debugging, you could add complete: function(){alert('complete');} to see if the request completes or not. Good debugging tools (add-ons) for Firefox are Live http headers and Firebug.


i think u need to specify as below in your jquery.ajax :

dataType: 'json'

 $("#but").click(function () {
            $.ajax({
                url: "/Home/SuccesMsg",
                dataType: 'json', // change code
                type: 'POST',
                data: "",
                success: function (result) {
                    if (result['Success'] == true) {
                        alert('success');
                    }

                    else
                    { alert('no'); }
                },
                error: function (err) { alert('error') }
            });
        });


Just tested this and it should work. You want

if (result.Success) {....}

instead of

if (resultJson['Success'] == true) {..}

So entire example

[HttpPost]
    public JsonResult SuccesMsg()
    {
        return Json(
            new
            {
                Success = true
            }
        );
    } 

$.ajax({
    url: '/Home/SuccesMsg',
    type: 'POST',
    success: function (result) {
        if (result.Success) {
            alert('success');
        } else {
            alert('no');
        }
    },
    error: function () {
        alert('error');
    }
});

You should also specify the dataType but not required: http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests


In MVC2 use JsonRequestBehavior.DenyGet has said here

  [HttpPost]
    public JsonResult SuccesMsg()
    {
        return Json(new { Success = true }, JsonRequestBehavior.DenyGet);
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜