我是JQuery和JSON的新手。
我想从我的服务器中检索JSON,并在HTML文件的不同标题中显示每个部分。我不完全确定如何做到这一点,尝试了很多东西,我已经设法得到它,所以JSON显示在Chrome的控制台日志中。
现在我真的不明白我如何抓住每个单独的JSON部分来显示在不同的div中。任何帮助,将不胜感激。
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("http://10.240.211.221:5000/questions/1", function(result){
console.log(result);
});
});
});
</script>
</head>
<body>
<button>Get JSON data</button>
<h1 id="question">Question will go here</h1>
<div id="optionA">
option A will go here
</div>
<div id="optionB">
option B will go here
</div>
</body>
</html>
JSON
{
"question": [
{
"ID": 1,
"a": "Yes",
"aResult": 0,
"b": "No",
"bResult": 0,
"question": "Are Jaffa Cakes biscuits?"
}
]
}
单击按钮时,我收到'Uncaught TypeError:无法读取未定义的属性'0'。 这可能是什么原因造成的? – RafeeJ
我根据你最初的问题写了这个例子。你必须检查你的反应结果是什么。我将'question'定义为'var question = result.questions [0];'所以我假设结果没有数组问题。 – zlwaterfield
我应该指定该结果在我原来的问题中返回JSON。它确实返回一些东西。 – RafeeJ