我们想要实现在textarea里输入的时候,后台检查这个输入并且返回给前端。
那么textarea是这样写的:
<form>
<textarea id="codeTextarea" rows="20" cols="55"
spellcheck="false" onkeyup="getandShowText(this.value)" >
this is a big problem
</textarea>
</form>
返回给前端的位置目前还没设计,不过给它一个div,id为textHint.
现在需要实现ajax:
<script>
function getandShowText(str){
var xmlhttp;
if (str.length==0){
document.getElementById("textHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
// IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码
xmlhttp=new XMLHttpRequest();
}
else
{
// IE6, IE5 浏览器执行代码
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("textHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","/textarea",true);
xmlhttp.setRequestHeader("Content-Type"
, "application/x-www-form-urlencoded");
// 发送请求
xmlhttp.send("str="+str);
}
</script>
后端如下:
package com.promusician.web;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@Controller
@RequestMapping("/textarea")
public class TextareaController {
static Logger logger= Logger.getLogger(TextareaController.class.getName());
@RequestMapping(method = RequestMethod.POST)
public void getText( HttpServletResponse response, HttpServletRequest request, Model model) throws IOException {
//response
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println("恭喜");
out.flush();
out.close();
//request
request.setCharacterEncoding("UTF-8");
String s=request.getParameter("str");
logger.debug(s);
}
}
现在就完成了,因为我们不希望刷新页面,所以用void方法。