zoukankan      html  css  js  c++  java
  • springboot restful jsonp 跨域请求

    服务端:

    package dd.springboot.demo.controller.userInfo;
    import com.google.gson.Gson;
    import dd.springboot.demo.models.ZtUser;
    import dd.springboot.demo.services.UserServices;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import javax.servlet.http.HttpServletRequest;
    
    @Controller
    public class UserInfoController {
        @Autowired
        UserServices userServices;
        @RequestMapping(value = "/user/{id}")
        @ResponseBody
        public String getUser(@PathVariable("id") Integer id, HttpServletRequest request) {
            ZtUser user = userServices.selectByPrimaryKey(id);
            Gson gson = new Gson();
            String callback = request.getParameter("callback");
            String resultValue = callback + "("+gson.toJson(user)+")";
            return resultValue;
        }
    }
    

    客户端:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script type="text/javascript" src="../Scripts/jquery-3.3.1.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#btn").click(function () {
                    $.ajax({
                        type: "Get",
                        dataType: "Jsonp",
                        jsonp: "callback",
                        url: "http://localhost:8080/user/1?callback=?",
                        success: function (data) {
                            document.write(JSON.stringify(data));
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(XMLHttpRequest.status);
                            alert(XMLHttpRequest.readyState);
                            alert(textStatus);
                        }
                    })
                })
            })
        </script>
    </head>
    <body>
        <input type="button" value="点我" id="btn" />
    </body>
    </html>

    运行结果:


  • 相关阅读:
    项目下目录正确,却出现404
    Operation not allowed after ResultSet closed 结果集关闭异常
    Could not autowire.No beans of 'ItemsService' type found
    python,hashlib模块
    Ajax PHP项目实战
    PHP的数据类型总结
    解析导航栏的url
    PHP--冒泡、选择、插入排序法
    jQuery(二) jQuery对Ajax的使用
    easyui(一) 初始easyui
  • 原文地址:https://www.cnblogs.com/xinting/p/12536157.html
Copyright © 2011-2022 走看看