[英]When i enter value into textbox and hit submit i want that value below the textbox using ajax
Welcome.jsp
这是我的jsp页面。 当我在文本框中输入一个值并按Enter时,我希望该名称与<p>
标记一起显示。 我是ajax的新手。 请帮助我,我们可以将模型发送到ajax吗?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<script>
function ajaxCall()
{
//alert("in js");
$.ajax({
type: "GET",
url: "/welcomePage",
data: "name=" + $('#name').val(),
success: function(data)
{
alert("success !");
$('#show').html(data);
},
error: function()
{
alert("Error");
}
});
return false;
}
</script>
<body>
<h2 align="center">Welcome to Spring MVC</h2>
<form>
<input type="text" name="name" />
<input type="submit" value="submit" onclick="ajaxCall();"/>
</form>
<p>Your name is</p><div id="show"></div>
</body>
</html>
DemoController.java
package com.demo.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class DemoController {
@RequestMapping(value="/welcomePage" , method=RequestMethod.GET)
public @ResponseBody String showPage(
HttpServletRequest request,
HttpServletResponse response)
{
String name = request.getParameter("name");
/*ModelAndView model = new ModelAndView("Welcome");
model.addObject("name",name);
System.out.println("Name is:"+name);*/
return name;
}
}
在表单中提交类型按钮提交表单到它的操作 URL,如果没有指定URL,当前URL被重新加载。 当表单提交的当前页面上下文(DOM,CSS,JS)被破坏时,简而言之,提交表单时当前页面无法执行任何操作。
您需要做的就是阻止表单提交自己
为此,您可以向其onsubmit事件返回false,如下所示
<form onsubmit="return false;">
<input type="text" name="name" />
<input type="submit" value="submit" onclick="ajaxCall();"/>
</form>
从外观上看,其他所有内容都是正确的,因此在进行了此简单更改后,它应该可以使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.