最简单的方法来获取JSON并使用JQuery和Javascript对其进行解析? [英] Easiest way to get json and parse it using JQuery and Javascript?

查看:49
本文介绍了最简单的方法来获取JSON并使用JQuery和Javascript对其进行解析?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使这段代码被删除,但我似乎无法弄清楚.目标是以最简单,最简单的方式返回并解析json对象.这是代码段.

I am trying to get this code snipped to work but I can't seem to figure this out. The goal is to return and parse a json object in the most simple, easiest way possible. Here is the code snippet.

<!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>

更新:

在下面提供的所有帮助下,我已经弄清楚了,谢谢!我将在以后的案例中发布解决方案.问题是因为我没有遵循同一个起源策略",所以我忘记了回调.

I was able to figure it out with all of the assistance down below, Thank you! I will post the solution for future cases. The problem was that I had forgotten about the callback since I wasn't following Same Origin Policy.

<!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>

推荐答案

obj对象是array,因此您必须使用indexes访问元素.

obj object is an array so you have to access an element using indexes.

document.getElementById("demo").innerHTML = obj[0].id;

此外,您不需要JSON.parse方法,因为返回回调的data已经是json对象.

Also, you do not need JSON.parse method because data returned to callback is already a json object.

这篇关于最简单的方法来获取JSON并使用JQuery和Javascript对其进行解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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