简体   繁体   English

如何从AJAX响应中选择变量

[英]How to select a variable from an AJAX response

I have the following response from an AJAX request (as per Chrome console): 我收到来自AJAX请求的以下响应(根据Chrome控制台):

`XMLHttpRequest {
statusText: "Not Found", 
status: 404, 
responseURL: "XXX", 
response: "{"apiVersion":"2.1","error":{"code":404,"message":…dException","internalReason":"User not found"}]}}", responseType: ""…`}

How can I select both the value of statusText and the internalReason ? 如何选择statusTextinternalReason的值?

When I try to set var msg = response.data.statusText; 当我尝试设置var msg = response.data.statusText; I get Uncaught TypeError: Cannot read property 'statusText' of undefined 我收到Uncaught TypeError: Cannot read property 'statusText' of undefined

Edit: Here's the code in context: 编辑:这是上下文中的代码:

$.ajax({
    type: "GET",
    url: yt_url,
    dataType:"json",

    success: function(response)
    {
    // code
    }
    error: function(response)
    {
    handleError(response);
    }
 });


function handleError(response) {
    var msg = response.data.statusText;
    $('#status').html('An error occurred:' + msg);
}

You have the data in a string. 您有一个字符串中的数据。 If you want to access it like an object, then you have to convert it into one. 如果要像访问对象一样访问它,则必须将其转换为一个对象。

You need to find, or write, a parser for whatever data format the data is in. 您需要查找或编写解析器,以解析数据所处的数据格式。

It looks like it is JSON, so you can use JSON.parse(string) 看起来像是JSON,因此您可以使用JSON.parse(string)

如果您的json是有效的对象,那么您应该像这样访问:

var msg = response.statusText // not response.data.statusText as there is not key as data

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM