jQuery.ajax响应数据未定义 [英] jQuery.ajax response data is undefined

查看:320
本文介绍了jQuery.ajax响应数据未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的控制器操作中的代码:

Here is the code in my Controller Action:

[HttpPost]
public JsonResult MyAction()
{
    try
    {
        // Do something...

        return Json(new { Success = true });
    }
    catch(Exception ex)
    {
        return Json(new { Error = ex.Message });
    }
}

而且,这是我的脚本:

<script>
    $.ajax({
        type: "POST",
        url: '@Url.Action("MyAction", "MyController")',
        dataType: 'json'
    }).done(function (data) {
        alert(data.Success);
    }
    })
    .fail(function (data) {
        alert(data.Error);
    });
</script>

这成功完成(警报正确显示为"true"),但是当操作失败时,alert(data.Error)显示Undefined.

This works on success (the alert correctly shows "true"), but when the action fails, alert(data.Error) shows Undefined.

使用FireBug,我可以看到JSON数据已正确返回.为什么data.Error为未定义"?

Using FireBug, I can see that the JSON data is correctly returned. Why is data.Error "Undefined" then?

更新:

这是console.log(data)的输出:

readyState
4
responseText
"{"Error":"Attempted to divide by zero."}"
status
500
statusText
"Internal Server Error"
abort
function()
always
function()
complete
function()
done
function()
error
function()
fail
function()
getAllResponseHeaders
function()
getResponseHeader
function()
overrideMimeType
function()
pipe
function()
progress
function()
promise
function()
setRequestHeader
function()
state
function()
statusCode
function()
success
function()
then
function()

更新2:

对不起,我的代码出了点问题(不是这里的代码,而是我正在运行的代码). console.log(data)的正确输出是这样的:

Sorry, there was something wrong with my code (not the code here, but the code I was running). The correct output from console.log(data) is this:

Object {Error="Some error."}

推荐答案

来自服务器的两个响应都是成功的json响应.就客户端而言,有关该请求的所有信息均未失败.试试这个:

Both responses from the server are successful json responses. As far as the client is concerned, nothing about the request has failed. Try this:

$.ajax({
    type: "POST",
    url: '@Url.Action("MyAction", "MyController")',
    dataType: 'json'
}).done(function (data) {
    if (data.Success) {
        alert('success!');
    } else {
        alert(data.Error);
    }
})

这篇关于jQuery.ajax响应数据未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆