2012-09-10 51 views
2

這是從哪兒我嘗試inser用戶Ajax和Spring MVC的不工作

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> 
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<!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"> 
     <title>Add Users using ajax</title> 
     <script src="/Spring3MVC/js/jquery.js"></script> 
     <script type="text/javascript"> 
     function doAjaxPost() { 
      // get the form values 
      var firstName = $('#firstName').val(); 
      var lastName = $('#lastName').val(); 

      $.ajax({ 
       type: "POST", 
       url: "/insert", 
       data: "firstName=" + firstName + "&lastName=" + lastName, 
       success: function(response) { 
        // we have the response 
        $('#info').html(response); 
        $('#firstName').val(''); 
        $('#lastName').val(''); 
       }, 
       error: function(e) { 
        alert('Error: ' + e); 
       } 
      }); 
     } 
     </script> 
    </head> 
    <body> 
     <h1>Add Person</h1> 
     <table> 
      <tr><td>First Name : </td><td> <input type="text" id="firstName" name="firstName" /><br/></td></tr> 
      <tr><td>Last Name : </td><td> <input type="text" id="lastName" name="lastName" /> <br/></td></tr> 
      <tr><td colspan="2"><input type="button" value="Add Users" onclick="doAjaxPost()"><br/></td></tr> 
      <tr><td colspan="2"><div id="info" style="color: green;"></div></td></tr> 
     </table> 
     <a href="/SpringMVC/search">Show All Users</a> 
    </body> 
</html> 

我的jsp這是我的控制器代碼

@RequestMapping(value="/insert", method = RequestMethod.POST) 
public String insertPerson(ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam("firstName") String firstName, @RequestParam("lastName") String lastName) { 
    personDao.savePerson(firstName,lastName); 
    model.addAttribute("nameAdded", firstName+" "+lastName); 
    return "personAdded"; 
} 

當我點擊「添加用戶」按鈕, 什麼都沒發生。任何人都可以幫我解決這個問題嗎?

+0

你期待它發生了什麼? – gigadot

+0

點擊後,我想讓它去控制器代碼.. – user1514499

+0

你永遠不會調用'doAjaxPost()',是嗎? – sp00m

回答

6

您在除Ajax帖子以外的任何地方都使用上下文網址。

應該

url: "/insert",

也許是

url: "/SpringMVC/insert",

甚至更​​好

url: "<spring:url value='/insert' />",

+0

仍然沒有任何反應。 – user1514499

+0

然後我建議你得到一些很好的javascript調試工具(比如帶有FireBug插件的FireFox)並開始調試你的代碼和網絡流量。 – pap

4

嘗試

data: {firstName: firstName, lastName: lastName},

代替

data: "firstName=" + firstName + "&lastName=" + lastName,

在你的Ajax調用

3

使用JSP中url爲AJAX請求爲:

url: "insert" 

代替:

url: "/insert" 

您正在使用的是指向服務器的根絕對URL,而不是你的控制器。

我已經測試過它,它對我的​​代碼工作正常。

2

這兩個網頁的絕對網址是什麼,如果你在你上面按f12鍵keybourd,你可以跟蹤ajax調用並跟蹤響應代碼,如果它是200,那麼你的服務器端代碼沒有問題現在檢查成功功能,否則檢查服務器代碼,並且課程404意味着它沒有到達服務器。