我使用eclipse kepler ide在Spring MVC 3中遇到Ajax调用控制器的问题。我在youtube上找到了一些辅导,并制作了学习项目。我有早期的问题,当我有Ajax调用控制器,但一段时间后正常工作。我的项目是在Spring MVC项目中完成的,我有所有请求jar,只是没有用Ajax调用命中控制器。这是我的conf文件,控制器方法和jquery中的ajax调用
的web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
servlet的context.xml中
<mvc:resources location="/resources/" mapping="/resources/**"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<context:component-scan base-package="com.milan.springajax.controller" />
我的控制器方法
@RequestMapping(value="/getJSON/{firstName}/{lastName}", method=RequestMethod.GET)
public @ResponseBody
Contact findByName(@PathVariable("firstName") String first, @PathVariable("lastName") String last,
HttpServletRequest request, HttpServletResponse response){
Contact contact=contactService.findByName(first, last);
return contact;
}
和ajax调用位于<script>
标记
$(document).ready(function () {
$('.button').on('click', function () {
var first=$('#firstInput').val();
var last=$('#lastInput').val();
alert("button je stisnut " + first + " " + last);
$.ajax({
type:"GET",
url:'${pageContext.request.contextPath}/getJSON/' + first + "/" + last,
dataType:'json',
success: function(result) {
var contact = "id: " + result.id +
" | name : " + result.firstName + " " result.lastName +
" | age : " + result.age;
$('#theJson').html(contact);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Contact " + textStatus + errorThrown + " !");
} in thise line i get warning that i miss semicolon ???
});
});
});
和同一jsp页面中的html元素
<div>
<label for="firstInput">First Name</label>
<input type="text" name="firstName" id="firstInput">
</div>
<div>
<label for="laststInput">Last Name</label>
<input type="text" name="lastName" id="lastInput">
</div>
<div id="theJson"></div>
<button type="button" class="button" id="button">Fetch JSON</button>
其他人是否有使用spring mvc在eclipse中没有响应的ajax调用的问题,就像调用thisa ajax方法时没有点击右url地址一样。
答案 0 :(得分:0)
从网址${pageContext.request.contextPath}
${pageContext.request.contextPath}/getJSON/' + first + "/" + last
它不能在JS文件中工作,instaed,直接替换你的应用程序上下文:
your-app/getJSON/' + first + "/" + last
或
/getJSON/' + first + "/" + last