springboot ajax 返回 json 弹新页面

2017-12-15 23:40:12 +08:00
 kzyuan

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

来看看代码吧

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: youremail@domain.com">
                </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>


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

5713 次点击
所在节点    Java
6 条回复
nazor
2017-12-15 23:44:33 +08:00
因为 form 里还有 action ……
580a388da131
2017-12-16 00:34:30 +08:00
Ajax 返回后表单又提交了呗
Mitt
2017-12-16 01:42:56 +08:00
事件里调用 e.preventDefault(); 或者在 onsubmit 里 return false;
kzyuan
2017-12-16 11:22:06 +08:00
@Mitt 晚上回去看看
smy769
2017-12-21 17:46:36 +08:00
form 里还有 action 并且你的按钮是 submit 默认点击会提交 form
kzyuan
2017-12-21 19:15:30 +08:00
问题已解决,谢谢大家了。按钮 设置成 submit 了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/415189

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX