我在解析JSON时出错了
16lz
2021-01-22
I have this sample JSON code and I want to loop it through with jQuery AJAX but for some reason there is always error on console
我有这个示例JSON代码,我想用jQuery AJAX进行循环,但由于某些原因,控制台总是出现错误。
this is the codes in file new_content.json
这是文件new_content.json中的代码
[
{
"name": "Mehmet",
"email": "mehmet@gmail.com"
},
{
"name": "Fareed",
"email": "fareed3242@yahoo.com"
},
{
"name": "Jonathan",
"email": "jonathan@gmail.com"
}
]
these are my html
这些是我的html
<div id="main">This is the original text when page loads</div>
<button id="button1" type="button">Update content with Ajax</button>
this is inside javascript
这是内部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);
}
});
});
});
3 个解决方案
#1
3
There are 2 mistakes
有两个错误
- First remove
JSON.parse()
you donot need to parse it. - 首先删除JSON.parse(),不需要解析它。
- iterating the data
item[i].name
is incorrect it should beitem.name
anditem.email
. - 重复数据项[i].name不正确,应该是item.name和item.email。
Apart from the 2 listed above you were missing the closing parenthesis of .each
too if that was not a typo.
除了上面列出的两个之外,如果不是错别字,你也会错过。
Run the following and everything will be fine i just confirmed it on my local machine
运行以下命令,一切都会好的,我只是在本地机器上确认了。
$(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);
}
});
});
});
更多相关文章
- 想要改进我的jQuery代码,做我想要的,太丑了,IMO
- JQuery的一些基本功能代码(CH1&2)
- 如何在angularjs代码中单元测试jquery元素
- jquery常用代码片段
- Webhoster插入了一个javascript,它会阻止我的代码如何删除它?
- 可以直接拿来用的15个jQuery代码片段
- 为什么使用observe_field代码不能使用JQuery模型对话框?
- jquery 生成table表格 部分代码
- 使用jquery的$ .ajax来获取node.js脚本的输出,而不是它的代码