html - 在html页面中显示ajax
问题描述
我使用flask作为后端,我的端点之一是objectList,它以这种格式返回数据:
[{name1:value1, name2:value2}, {name1:value3, name2:value4}]
为了在我的 html 页面上显示此数据,我使用以下代码:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
$("#div1").html(result);
};
});
};
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
这不显示任何数据。我做错了什么,我该如何解决?
编辑:只是澄清一下,我希望在页面加载时加载数据,而不是在按钮或点击上
解决方案
经过我们的讨论,我发现这段代码可以正常工作
您必须关闭函数 ajax 中的括号,并使用此行允许服务器端的访问控制
header("访问控制允许来源:*");
// 或者将星号替换为您拥有 html 的服务器
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'localhost:5000/objectList',
method:"GET",
success: function(result){
// to verifiy the result
console.log(result);
var htmlOutput = '';
// the iteration of your result because you have many entries
$.each(result, function(i, item) {
htmlOutput += ''+
'<ul>'+
'<li>name1: '+item['name1']+'</li>'+
'<li>name2: '+item['name2']+'</li>'+
'</ul>';
});
$("#div1").html(htmlOutput);
}, error: function(jqXHR, textStatus, error) {
// to verifiy either there is an error or not
console.error(textStatus);
}
});
});
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
推荐阅读
- python - 运行此 python 代码后无法通过所有测试用例
- datatables - 带引号的数据表搜索和过滤问题
- html - 我应该如何使用 aria-label?
- python - Python转换的exe如何去掉鹅毛笔图标
- java - 使用 Jersey 3.0.1 在 Java 中运行简单的 RESTful Web 服务时,显示 HTTP 状态 404 错误
- python - 不断收到 IndexError 消息?
- angular - 讨人喜欢的 rxjs 订阅者
- html - 纯 HTML/CSS 树形布局
- python - 当列长度不同时,将一个 pandas 列的值映射到另一列
- javascript - Wordpress 问题中可能存在的 jQuery