首页 > 解决方案 > 在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>

这不显示任何数据。我做错了什么,我该如何解决?

编辑:只是澄清一下,我希望在页面加载时加载数据,而不是在按钮或点击上

标签: htmlajaxflask

解决方案


经过我们的讨论,我发现这段代码可以正常工作

您必须关闭函数 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>


推荐阅读