![](/img/trans.png)
[英]why is that when I save a code file in VS code as a .js file it wont run or open in a browser?
[英]Why my json data wont appear in browser when i run the code
我的json数据不会出现在浏览器中。 这是我第一次使用json,我无法找出问题所在。我在互联网上进行搜索,发现它与mime有关,但仍然无法解决。 这是代码:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var jsonData = '[{"rank":"9","content":"Alon","UID":"5"},{"rank":"6","content":"Tala","UID":"6"}]';
$.ajax({
url: '/echo/json/',
type: 'POST',
contentType:"application/json; charset=utf-8",
data: {
json: jsonData
},
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
});
$('#records_table').append(trHTML);
}
});
</script>
</head>
<body>
<table id="records_table" border='1'>
<tr>
<th>Rank</th>
<th>Content</th>
<th>UID</th>
</tr>
</table>
</body>
</html>
这是更新的代码
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var jsonData = '[{"rank":"9","content":"Alon","UID":"5"},{"rank":"6","content":"Tala","UID":"6"}]';
$(document).ready(function(){
$.ajax({
url: '/echo/json/',
type: 'POST',
contentType:"application/json; charset=utf-8",
data: {
json: jsonData
},
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
});
$('#records_table').append(trHTML);
}
});
});
</script>
</head>
<body>
<table id="records_table" border='1'>
<tr>
<th>Rank</th>
<th>Content</th>
<th>UID</th>
</tr>
</table>
</body>
</html>
您在ajax调用周围缺少文档就绪块。
编写一个Error方法,看看是否发生了一些ajax错误
`$.ajax({
success: function(){
// Handle the success event
},
error: function(xhr){
// Handle the error event
}
// ......
});`
xhr将显示响应文本
更新:
您的代码完全正确,就像nikhil所说的dodument.ready应该是魔术
检查我用您的代码测试过的小提琴http://jsfiddle.net/8sfm0p14/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.