我试图让这段代码破解工作,但我似乎无法解决这个问题。目标是以最简单,最简单的方式返回和解析json对象。这是代码段。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
</head>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
$.getJSON('http://finance.google.com/finance/info?client=ig&q=NASDAQ:TSLA', function(data) {
var obj = JSON.parse(data);
document.getElementById("demo").innerHTML = obj.id;
});
</script>
</body>
</html>
更新:
我能够通过下面的所有帮助找到答案,谢谢!我将为未来案例发布解决方案。问题是我忘记了回调,因为我没有遵循同源策略。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>
<script>
$(document).ready(function () {
$.getJSON('https://www.google.com/finance/info?q=NASDAQ:TSLA&callback=?', function(data) {
$('#demo').text(data[0].id);
});
});
</script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
答案 0 :(得分:3)
obj
对象是array
,因此您必须使用indexes
访问元素。
document.getElementById("demo").innerHTML = obj[0].id;
此外,您不需要JSON.parse
方法,因为返回回调的data
已经是json
个对象。
答案 1 :(得分:1)
您问题中的代码可能是解析请求中预期的JSON
数据的最短方式。该快捷方式来自:
var http = $.ajax({
url: 'http://finance.google.com/finance/info?client=ig&q=NASDAQ:TSLA',
dataType: "json" //This is what makes jQuery parse the data in the expected format
});
http.done(function(data){
// data is already parsed as JSON
$("#demo").text(data.id);
});
编辑:刚才我检查了您的请求的响应,结果发现它是一个注释JSON Array
,因此这将使解析失败。
为了实际解析注释的JSON
响应,内容必须删除使得内容被评论的初始字符,之后,最终可以解析响应并提取所需的数据
// the respone will come as string format and jQuery ajax will try to guess what's the dataType from
// the response, just to be sure i will ask Ajax to get the data as String (this is not necessary)
var http = $.ajax({
url: 'http://finance.google.com/finance/info?client=ig&q=NASDAQ:TSLA',
dataType: "string"
});
http.done(function(data){
// slice the first 3 chars which makes the JSON to be commented
var json = data.slice(3);
// now this JSON is finally a valid JSON, so it can be parsed
data = JSON.parse(json);
// the data is now an Array of 1 element, we can now extract and print the data this way
if(data.length == 1){
$("#demo").text(data[0].id);
// to print data using native Javascript
document.getElementById("demo").innerText = data[0].id;
}
// in case the Array has more than 1 element and yet you want to print all of them,
// you can iterate the Array
for(i = 0; data.length > i; i++){
var d = data[i];
// do something the the iterated data
}
});