欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript 用ajax传递参数到后台

程序员文章站 2022-04-02 22:21:15
...

用ajax传递参数时,会经常出现后台接受不到参数的情况,解决如下

前端:

  <script type="text/javascript">
    var validateNum;
    function validateButton() {
        if (validateNum!=null){
                if (document.getElementById("validateNum").value==validateNum){
                    var c=document.getElementById('submit');
                    c.type='submit';
                }else {
                    alert("不对");
                }
            }
    }
    function success(text) {
        validateNum=text;
    }
    function fail(code) {
        var input = document.getElementById('test-response-text');
        alert(code);
    }
    function startRequst1(){
        var request = new XMLHttpRequest(); // 新建XMLHttpRequest对象
        request.onreadystatechange = function () { // 状态发生变化时,函数被回调
            if (request.readyState === 4) { // 成功完成
                // 判断响应结果:
                if (request.status === 200) {
                    // 成功,通过responseText拿到响应的文本:
                    alert(request.responseText);
                    return success(request.responseText);
                } else {
                    // 失败,根据响应码判断失败原因:
                    return fail(request.status);
                }
            } else {
                // HTTP请求还在继续...
            }
        };
        // 发送请求:
        var phoneNumber=document.getElementById("phoneNumber").value;
        request.open('POST', '/blog/sendValidateMsg',true);
        request.setRequestHeader("Content-type", "application/json; charset=utf-8");
        request.send(phoneNumber);//传递单个参数
    }
</script>
<body>

<div class="body-mid-form">
            <form action="/blog/register1" method="post">
                <input type="text"   placeholder="请输入手机号码" id="phoneNumber" name="phoneNumber"/>
                <br/>
                <input type="text" placeholder="请出入验证码" id="validateNum"/>
                <input type="button" value="点击获取验证码" onclick="startRequst1();"/>
                <br/>
                <input type="text" placeholder="请输入密码" id="password" name="password"/>
                <br/>
                <input type="button" value="注册" id="submit" onclick="validateButton()"/>
            </form>
</div>
</body>
</html>

后台获取ajax传递来的参数:

        @ResponseBody
	@RequestMapping("/blog/sendValidateMsg")
	public String  sendValidateMsg(HttpServletRequest req){
		//ajax传递过来的参数 的读取
		StringBuilder sb = new StringBuilder();
		try {
			BufferedReader reader = req.getReader();
			char[]buff = new char[1024];
			int len;
			while((len = reader.read(buff)) != -1) {
				sb.append(buff,0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();//这便是传递过来的值

	}

当用ajax传递多个值时:

request.send(JSON.stringify({ "phoneNumber": "1123546", "name": "Lucy" }));

后台接收:

                 StringBuilder sb = new StringBuilder();
                 try {
			BufferedReader reader = req.getReader();
			char[]buff = new char[1024];
			int len;
			while((len = reader.read(buff)) != -1) {
				sb.append(buff,0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		String str=sb.toString();
		JSONObject jsonObject=new JSONObject(str);
		String  phoneNumber=jsonObject.getString("phoneNumber");          
                String  name=jsonObject.getString("name"); 
                //含有特殊字符的文本需要先进行转码
               URLDecoder.decode(jsonObject.getString("text"), "UTF-8"));