V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
kzyuan
V2EX  ›  Java

springboot ajax 返回 json 弹新页面

  •  
  •   kzyuan ·
    ykz200 · 2017-12-15 23:40:12 +08:00 · 5879 次点击
    这是一个创建于 2538 天前的主题,其中的信息可能已经有所发展或是发生改变。

    返回完结果就是这个样子,不走 ajax 后续的判断 m0zOa.png

    来看看代码吧

    java 代码
     
    import com.bhusk.black.model.CompanyInfo;
    import com.bhusk.black.model.StatusBean;
    import com.google.code.kaptcha.impl.DefaultKaptcha;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.imageio.ImageIO;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayOutputStream;
     
    @Controller
    @RequestMapping("/api")
    public class ApiVerification {
     
    
        /**
         * 
         *
         * @param request
         * @param response
         * @param companyInfo 传递的公司信息
         * @return
         */
    
        @RequestMapping(value = "/putCompany", method = RequestMethod.POST)
        @ResponseBody
        public StatusBean apiPutInfo(HttpServletRequest request, HttpServletResponse response, CompanyInfo companyInfo) {
    
            StatusBean<String> statusBean = new StatusBean<String>();
    
            String captchaId = (String) request.getSession().getAttribute("vrifyCode");
            String parameter = request.getParameter("vrifyCode");
            System.out.println("Session  vrifyCode "+captchaId+" form vrifyCode "+parameter);
    
            if (!captchaId.equals(parameter)) {
                statusBean.setMessage("错误的验证码");
                statusBean.setStatus(false);
                return statusBean;
            } else {
                statusBean.setMessage("成功");
                statusBean.setStatus(true);
            }
            /**
             * api 接口保存 post 的数据信息
             */
     
            System.out.println("保存成功");
            return statusBean;
        }
    }
    
    
    
    html 代码
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>申请收录</title>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <meta name="fragment" content="!">
        <link rel="icon" type="image/x-icon" href="${request.contextPath}/static/favicon.ico">
        <link href="${request.contextPath}/static/css/demo.css" rel="stylesheet" type="text/css">
        <!--Framework-->
        <script src="${request.contextPath}/static/js/jquery-1.9.1.js" type="text/javascript"></script>
        <script src="${request.contextPath}/static/js/jquery-ui.js" type="text/javascript"></script>
        <!--End Framework-->
        <script src="${request.contextPath}/static/js/jquery.ffform.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $('#form').ffform({
                    animation: 'flip',
                    submitButton: '#submit',
                    validationIndicator: '#validation',
                    errorIndicator: '#error',
                    successIndicator: '#success',
                    'fields': [{
                        'id': 'name',
                        required: true,
                        requiredMsg: 'Name is required',
                        type: 'alpha',
                        validate: true,
                        msg: 'Invalid Name'
                    }, {
                        'id': 'email',
                        required: true,
                        requiredMsg: 'E-Mail is required',
                        type: 'email',
                        validate: true,
                        msg: 'Invalid E-Mail Address'
                    }, {
                        'id': 'phone',
                        required: false,
                        type: 'custom',
                        validate: false,
                        msg: 'Invalid Phone #'
                    }, {'id': 'message', required: false, type: 'text', validate: false, msg: ''}]
                });
            });
        </script>
    </head>
    <body>
    
    <section id="getintouch">
        <div class="container" style="border-bottom: 0;">
            <h1>
                <span> IT'S FREE!</span>
            </h1>
        </div>
        <div class="container">
            <form class="contact" action="${request.contextPath}/api/putCompany" method="post" id="form">
                <div class="row clearfix">
                    <div class="lbl">
                        <label for="name">
                            公司名称</label>
                    </div>
                    <div class="ctrl">
                        <input type="text" id="companyName" name="companyName" data-required="true" data-validation="text"
                               data-msg="Invalid Name" placeholder="company name">
                    </div>
                </div>
    
                <div class="row clearfix">
                    <div class="lbl">
                        <label for="email">
                            地址</label>
                    </div>
                    <div class="ctrl">
                        <input type="text" id="position" name="position" data-required="true" data-validation="custom"
                               data-msg="Invalid Phone #" placeholder="address">
                    </div>
                </div>
                <div class="row clearfix">
                    <div class="lbl">
                        <label for="email">
                            E-Mail</label>
                    </div>
                    <div class="ctrl">
                        <input type="text" id="email" name="email" data-required="true" data-validation="email"
                               data-msg="Invalid E-Mail" placeholder="Ex: [email protected]">
                    </div>
                </div>
    
                <div class="row clearfix">
                    <div class="lbl">
                        <label for="remarks">
                            详细信息</label>
                    </div>
                    <div class="ctrl">
                        <textarea id="remarks" name="remarks" rows="6" cols="10"></textarea>
                    </div>
                </div>
                <div class="row clearfix">
                    <div class="lbl">
                        验证码
                    </div>
                    <div class="ctrl">
                        <img alt="验证码" onclick="this.src='${request.contextPath}/api/defaultKaptcha?d='+new Date()*1"
                             src="${request.contextPath}/api/defaultKaptcha"/>
                        <input type="text" style="width: 20%;margin-top: -5%;" name="vrifyCode" id="vrifyCode"
                               placeholder="验证码">
                    </div>
                </div>
                <div class="row  clearfix">
                    <div class="span10 offset2">
                        <input type="submit" class="submit" value="提交" onclick="login()">
                    </div>
                </div>
            </form>
    
            <div id="validation">
            </div>
        </div>
    </section>
    <script type="text/javascript">
        function login() {
    
            $.ajax({
                //几个参数需要注意一下
                type: "POST",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "${request.contextPath}/api/putCompany",//url
                data: $('#form').serialize(),
                async: false,
                success: function (result) {
    
                    // console.log(result);//打印服务端返回的数据(调试用)
                    alert(result)
                }, error: function () {
                    alert("服务器异常!");
                }
    
            })
    
        }
    
    
    </script>
    </body>
    </html>
    
    
    

    不懂哪里出问题了,为什么会打开一个新的页面。

    6 条回复    2017-12-21 19:15:30 +08:00
    nazor
        1
    nazor  
       2017-12-15 23:44:33 +08:00 via iPhone   ❤️ 1
    因为 form 里还有 action ……
    580a388da131
        2
    580a388da131  
       2017-12-16 00:34:30 +08:00   ❤️ 1
    Ajax 返回后表单又提交了呗
    Mitt
        3
    Mitt  
       2017-12-16 01:42:56 +08:00
    事件里调用 e.preventDefault(); 或者在 onsubmit 里 return false;
    kzyuan
        4
    kzyuan  
    OP
       2017-12-16 11:22:06 +08:00 via Android
    @Mitt 晚上回去看看
    smy769
        5
    smy769  
       2017-12-21 17:46:36 +08:00
    form 里还有 action 并且你的按钮是 submit 默认点击会提交 form
    kzyuan
        6
    kzyuan  
    OP
       2017-12-21 19:15:30 +08:00 via Android
    问题已解决,谢谢大家了。按钮 设置成 submit 了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   3101 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:04 · PVG 08:04 · LAX 16:04 · JFK 19:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.