jQuery.ajax 响应数据未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24170029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 02:28:56  来源:igfitidea点击:

jQuery.ajax response data is undefined

jqueryajaxasp.net-mvcjson

提问by ataravati

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 });
    }
}

And, here is my script:

而且,这是我的脚本:

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

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

这适用于成功(警报正确显示“true”),但当操作失败时,alert(data.Error)显示Undefined.

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

使用 FireBug,我可以看到正确返回了 JSON 数据。为什么是data.Error“未定义”呢?

UPDATE:

更新:

Here is the output from 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()

这是来自的输出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()

UPDATE 2:

更新 2:

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:

抱歉,我的代码有问题(不是这里的代码,而是我正在运行的代码)。正确的输出console.log(data)是这样的:

Object {Error="Some error."}

Object {Error="Some error."}

回答by Jason P

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

来自服务器的两个响应都是成功的 json 响应。就客户端而言,请求没有失败。尝试这个:

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

回答by devplayer

I just faced a similar problem. Investigating the response in Developer tools, i see that even though the parameter datawas passed as 'undefined' to the 'success' function call - the actual response body did contain the expected string.

我刚刚遇到了类似的问题。在开发人员工具中调查响应,我发现即使参数data作为“未定义”传递给“成功”函数调用 - 实际响应正文确实包含预期的字符串。

The response can be deeper investigated in the developer tools -Network Tab -> press 'Start Capturing' - and on the actual request record - click on 'Go to detailed view').

可以在开发人员工具中更深入地调查响应 - 网络选项卡 -> 按“开始捕获” - 在实际请求记录上 - 单击“转到详细视图”)。

The problem on my side resided in malformed Content-Typeheaders of the response. The response string was passed correctly, and was even correctly interpreted in other browsers (FF, Chrome, Safari). The headers set up on the server were, in this order:

我这边的问题在于响应的格式错误的 Content-Type标头。响应字符串被正确传递,甚至在其他浏览器(FF、Chrome、Safari)中也被正确解释。在服务器上设置的标头按以下顺序排列:

  Response.AddHeader "Content-type", "text/html;charset=UTF-8"
  Response.AddHeader "Content-type","application/json"
  Response.ContentType = "application/json"

The result received by the client (investigated in network detailed view, like above mentioned) was:

客户端收到的结果(在网络详细视图中调查,如上所述)是:

Content-Type    text/html;charset=UTF-8,application/json

It seems that IE (8,9) is picky about the headers, specifically the Content-Type.

IE (8,9) 似乎对标题很挑剔,特别是Content-Type

This lead in IE9, IE8 to the parameter databeing passed as undefinedand complete subsequent failure. As soon as i removed the unwanted headers, i.e. this line:

这导致在 IE9、IE8 中传递的参数数据undefined并完成后续失败。一旦我删除了不需要的标题,即这一行:

Response.AddHeader "Content-type", "text/html;charset=UTF-8"

The final conten-type received by the client was only:

客户端收到的最终内容类型仅为:

Content-Type    application/json

And finally, the data parameter in this part of the ajax call was no longer "undefined", but the expected "object"

最后,这部分ajax调用中的数据参数不再是“未定义”,而是预期的“对象”

success: function(data, textStatus, XMLHttpRequest){
  alert(typeof(data));
},

* The server-side scripting language in this case is ASP's VBscript, you should know your corresponding syntax for the server-side header setting in order to know what to look for *

* 在这种情况下,服务器端脚本语言是ASPVBscript,您应该知道服务器端标头设置的相应语法,以便知道要查找的内容 *

回答by PeterKA

Looking at the jSON return, it appears that you should be looking for data.responseText.Errorinstead:

查看 json 返回,您似乎应该寻找data.responseText.Error

alert( data.responseText.Error );

UPDATE

更新

Per the updated output, you're looking for the correct data but in the wrong call back. When you successfully handle exceptionson the server side you avoid having to deal will errors server-related errors on the client side.

根据更新的输出,您正在寻找正确的数据,但在错误的回调中。当您handle exceptions在服务器端成功时,您可以避免在客户端处理与服务器相关的错误。

As already pointed out, as far as your client-side code is concerned the request was successful and therefore you should be looking for data.Errorin the done callback. Change your code to:

正如已经指出的,就您的客户端代码而言,请求已成功,因此您应该data.Error在 done 回调中寻找。将您的代码更改为:

.done(function( data ) {
    !data.Success || alert( data.Success );
    !data.Error || alert( data.Error );
})