• 跨域问题


    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title></title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    </head>
    <body>
    <table id="tab" border="1">
    <tr>
    <th>编号</th>
    <th>名字</th>
    <th>年龄</th>
    <th>性别</th>
    </tr>
    </table>
    <button onclick="req()">请求数据</button>
    <img id="img" />
    </body>
    <script>
    function req(){
    document.getElementById("img").src = "img/timg.gif";
    $.ajax({
    url:"http://localhost:8080/MyServer/getData",
    success:function(data){
    data = JSON.parse(data)
    console.log(data)
    for (var i = 0; i < data.length; i++) {
    a = data[i];
    var row = "<tr><td>id</td><td>name</td><td>age</td><td>gender</td></tr>"
    row = row.replace("id",a.id);
    row = row.replace("name",a.name);
    row = row.replace("age",a.age);
    row = row.replace("gender",a.gender);
    document.getElementById("tab").insertAdjacentHTML("beforeend",row);
    }
    document.getElementById("img").src = "";
    },
    error:function(err){
    console.log(err);
    document.getElementById("img").src = "";
    }
    });
    }
    </script>
    </html>
     
    package com.kkb;

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;

    import java.io.IOException;
    import java.util.ArrayList;

    public class AServlet extends javax.servlet.http.HttpServlet {
        protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        }

        protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
            //允许来自任何主机的跨越访问
            response.setHeader("Access-Control-Allow-Origin","*");
    //设置响应类型为json数据
            response.setContentType("application/json;charset=utf-8");

            //学生信息
            ArrayList<Student> students = new ArrayList<>();

            Student stu1 = new Student("s1","jack",20,"man");
            Student stu2 = new Student("s2","tom",22,"girl");
            Student stu3 = new Student("s3","jerry",10,"woman");
            Student stu4 = new Student("s4","scot",24,"boy");
            students.add(stu1);
            students.add(stu2);
            students.add(stu3);
            students.add(stu4);
            response.getWriter().println(JSON.toJSONString(JSON.toJSONString(students)));
        }
    }
     
  • 相关阅读:
    分布式锁原理及实现方式
    【FAQ】Maven 本地仓库明明有jar包,pom文件还是报错解决办法
    【FAQ】tomcat启动jdk版本不一致
    【Map,HashMap,Vector,List】资料汇总
    【FAQ】调用接口序列化问题
    【docker】docker下安装mysql
    linux tcpdump抓包Post请求
    Springboot 在@Configuration注解的勒种 使用@Autowired或者@value注解 读取.yml属性失败
    Springboot使用Shiro-整合Redis作为缓存 解决定时刷新问题
    CentOS yum 安装nginx
  • 原文地址:https://www.cnblogs.com/huaobin/p/14162665.html
Copyright © 2020-2023  润新知