【发布时间】:2016-03-10 22:40:48
【问题描述】:
Welcome.jsp
这是我的jsp页面。当我在文本框中输入一个值并按回车键时,我希望名称与 <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;
}
}
【问题讨论】:
-
确保在“/welcomePage”之前添加一个“..”,这样如果解析到根目录,例如:“../welcomePage”,或者如果您想要当前目录并且welcomePage 是您的jsp文件使用:'welcomePage.jsp'
-
不,我的 jsp 文件是 Welcome.jsp。我会尝试 ../welcomPage .
-
它不起作用。当我按下提交按钮时,我收到一个错误警报。
-
也用于使用 Jquery .ajax 数据预计是一个对象,如
data: { name:'name'}fyi。将三个参数放入error函数中,并放置一个调试器语句,看看它们是什么。 -
localhost:8080/DemoApplication/?name=hello 这是我点击提交后 url 中出现的内容。它没有转到welcomePage url
标签: javascript ajax spring jsp model-view-controller