无法访问JSON响应属性 [英] Cannot access JSON response attribute

查看:74
本文介绍了无法访问JSON响应属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中有一个JSON响应,如下所示:

I have a JSON response in JavaScript that looks like this:

{"opt1":"2.92","opt2":"4.24","opt3":"6.36"};

这是应用console.log(data)的结果,其中数据是响应:

This is the result of applying console.log(data) where data is the response:

success: function(data){
            console.log("Ajax succeeded");
            console.log(data);
            console.log(data.opt1);
        },

但是,我无法访问opt1的值.控制台指示未定义.有什么想法可能会是这种情况吗? JSON有效,我检查了.

However, I cannot access the value of opt1. The console indicates undefined. Any ideas why this could be the case? The JSON is valid, I checked it.

编辑

在这种情况下,服务器使用PHP中的json_encode函数将数组转换为JSON.我尝试在最后删除分号,这仍然为我提供了opt1的未定义值.我还尝试设置ajax调用的dataType,这会导致错误,表明存在意外字符.

The server in this case uses the json_encode function in PHP to convert an array to JSON. I have tried removing the semicolon at the end, this still gives me an undefined value for opt1. I also tried setting the dataType of the ajax call, that results in an error, indicating there is an unexpected character.

推荐答案

听起来data实际上可能是字符串,而不是对象.

It sounds like data may actually be a string, not an object.

您需要做的两件事:

第一:如果该分号确实存在,则您得到的响应不是有效的JSON.您将需要通过删除分号服务器端来解决此问题. (但请参见下文.)

First: If that semicolon is really there, the response you're getting is not valid JSON. You'll want to fix that by removing the semicolon server-side. (But see below.)

第二:然后,您要确保将JSON字符串反序列化到一个对象中.几种方法可以做到这一点:

Second: Then, you'll want to make sure the JSON string is deserialized into an object. Several ways to do that:

  1. 如果您的服务器使用正确的Content-Type标头(application/json)进行答复,它将自动发生.这是最好的方法.

  1. It will happen automatically if your server replies with the correct Content-Type header (application/json). This is the best way.

如果由于某种原因不是这种情况,而您又无法做到,请将dataType: 'json'添加到您的ajax通话中.

If for some reason that's not the case and you can't make it the case, add dataType: 'json' to your ajax call.

如果由于某些原因您不能执行 操作,则可以通过

If for some reason you can't do that, you can manually parse the JSON string via $.parseJSON, e.g.:

data = $.parseJSON(data);

(请注意,如果parseJSON具有浏览器内置的JSON.parse,则会很高兴地使用它.如果浏览器没有内置的JSON.parse,则jQuery将使用其内置的.)

(Note that parseJSON will happily use the browser's built-in JSON.parse if it has one. If the browser doesn't have one, jQuery will use its own.)


如果由于某种原因您无法删除无效的;服务器端,则可以解决该问题:


If for some reason you can't remove the invalid ; server-side, you can work around it:

  1. dataType: 'text'添加到您的ajax通话

success中:

data = $.parseJSON(data.replace(/;$/, ''));

这将删除分号(如果存在的话),然后解析结果.

That will remove the semicolon if it's there, and then parse the result.

这篇关于无法访问JSON响应属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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