我有这个示例JSON代码,我想用jQuery AJAX循环它,但由于某种原因,控制台上始终存在错误
这是文件 new_content.json
中的代码[
{
"name": "Mehmet",
"email": "mehmet@gmail.com"
},
{
"name": "Fareed",
"email": "fareed3242@yahoo.com"
},
{
"name": "Jonathan",
"email": "jonathan@gmail.com"
}
]
这些是我的HTML
<div id="main">This is the original text when page loads</div>
<button id="button1" type="button">Update content with Ajax</button>
这是在javascript中
$(document).ready(function () {
$("#button1").on('click', function () {
$.ajax({
type: "GET",
url: "new_content.json",
success: function (rawData) {
var data = JSON.parse(rawData);
var result = '';
result += '<table> \
<tr> \
<th>name</th> \
<th>email</th> \
</tr> \
<tr>';
$.each(data, function (i, item) {
result += "<tr><td>" + item[i].name + "</td>";
result += "<td>" + item[i].email + "</td></tr>";
});
result += "</tr></table>";
$("#main").html(result);
}
});
});
});
答案 0 :(得分:3)
有2个错误
JSON.parse()
。item[i].name
不正确,应该是item.name
和item.email
。除了上面列出的2之外,如果不是拼写错误,你也错过了.each
的右括号。
运行以下内容,一切都会好的,我只是在本地机器上确认了
$(document).ready(function () {
$("#button1").on('click', function () {
$.ajax({
type: "GET",
url: "my.json",
success: function (rawData) {
var data = rawData;
var result = '';
result +=
'<table> \
<tr> \
<th>name</th> \
<th>email</th> \
</tr> \
<tr>';
$.each(data, function (i, item) {
result += "<tr><td>" + item.name + "</td>";
result += "<td>" + item.email + "</td></tr>";
});
result += "</tr></table>";
$("#main").html(result);
}
});
});
});
答案 1 :(得分:1)
问题来自每个循环的内部,你不需要使用[i]
你的循环应该是这样的:
$.each(data, function(i, item) {
result += "<tr><td>" + item.name + "</td>";
result += "<td>" + item.email + "</td></tr>";
})
希望这会有所帮助。
var data = [{
"name": "Mehmet",
"email": "mehmet@gmail.com"
},
{
"name": "Fareed",
"email": "fareed3242@yahoo.com"
},
{
"name": "Jonathan",
"email": "jonathan@gmail.com"
}
];
var result = "";
var result = '';
result += '<table><tr><th>name</th><th>email</th></tr><tr>';
$.each(data, function(i, item) {
result += "<tr><td>" + item.name + "</td>";
result += "<td>" + item.email + "</td></tr>";
})
result += "</tr></table>";
$("#main").html(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main"></div>
答案 2 :(得分:-1)
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided
('https://worker.mturk.com') does not match the recipient window's origin
('https://www.mturk.com').
试试这个。