【发布时间】:2013-03-24 07:48:08
【问题描述】:
我正在使用 XMLHTTPRequest 来获取 JSON 响应。当我在 Firebug 中查看 Response 选项卡时,它会显示我在 jsonlint 上验证过的 JSON 对象。当我尝试访问对象的属性时,我得到了
TypeError: obj 未定义
我研究了几个小时,但未能找到可行的解决方案。
代码:
function getState(light) {
var txt = execute('GET', 'http://' + bridge + '/api/' + hash + '/lights/' + light);
var obj = eval('(' + txt + ')');
//var obj = JSON.parse(txt);
//this gives me "SyntaxError: JSON.parse: unexpected character"
console.log(obj.name);
}
function execute($method, $url, $message) { //used for both PUT and GET requests
var xmlhttp = new XMLHttpRequest();
xmlhttp.open($method, $url, true)
xmlhttp.send($message);
console.log(xmlhttp.response);
return xmlhttp.response;
}
在Firebug Response选项卡中,表示GET请求的响应:200 OK -4ms
{
"state": {
"on": false,
"bri": 200,
"hue": 8664,
"sat": 140,
"xy": [0.4932, 0.3832],
"ct": 428,
"alert": "none",
"effect": "none",
"colormode": "hs",
"reachable": true
},
"type": "Extended color light",
"name": "Left rear living room 1",
"modelid": "LCT001",
"swversion": "65003148",
"pointsymbol": {
"1": "none",
"2": "none",
"3": "none",
"4": "none",
"5": "none",
"6": "none",
"7": "none",
"8": "none"
}
}
当我调用 getState 函数(在页面加载时)时,console.log 声称 xmlhttp.response 是一个空字符串。对 'txt' 和 'obj' 执行 typeof 会返回未定义。我正在尝试访问对象元素,例如:
obj.name 和 obj.state.on
我不熟悉使用 JSON 和 XMLHttpRequest - 我的代码基于其他人最初创建的模板。我对我在程序中其他地方使用上述函数的 PUT 请求没有任何问题,但似乎无法让 GET 请求正常工作。
如果我遗漏了任何重要信息,请告诉我。感谢您提供的任何帮助!
【问题讨论】:
-
'bridge'(服务器名)是相同的还是不同的机器名(和端口)?
-
我在
eval(之后停止阅读。叹息…… -
AJAX 中的第一个 A 代表 asynchronous
-
@Pointy:你是第一个在这里提到 AJAX 的人:P
-
我建议阅读XMLHttpRequest API 的一个很好的介绍。它可以阐明您的代码无法按预期工作的原因。
标签: javascript json get xmlhttprequest