【问题标题】:New JSP page is opened instead of loading JSP into DIV of current page打开新的 JSP 页面,而不是将 JSP 加载到当前页面的 DIV 中
【发布时间】:2016-05-09 12:33:17
【问题描述】:

我想在点击Submit 后将一些数据加载到 div users 中。为此,我使用 ajax。问题是页面http://localhost:8080/myprj/showUsers是在按钮点击事件上打开的,而不是将此内容加载到div中。

Context.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<script type="text/javascript">
function loadAjax() {       
    $.ajax({
        url: "context.do", 
        success: function(result) { 
            $("#users").html(result); 
        },
        error : function(e) {
            alert('Error: ' + e);
        }
    });
}
</script>
</head>
<body>

<h2>Context information</h2>
<form:form method="POST" action="/myprj/showUsers">
 <table>
    <tr>
        <td><form:label path="weather">Weather</form:label></td>
        <td><form:input path="weather" /></td>
    </tr>
    <tr>
        <td><form:label path="companions">Companions</form:label></td>
        <td><form:input path="companions" /></td>
    </tr>
</table>  
        <table border="1" cellspacing="1" align="center" style="margin-top: 160px;">
            <tr>
                 <th>Weather</th>
                 <th>Companions</th>
            </tr>
            <tr>
                 <td>${weather}</td>
                 <td>${companions}</td>
            </tr>
         </table>

<input type="submit" value="Submit" onclick="loadData()" />

</form:form>

<div id = "users"></div>

</body>
</html>

控制器

@Controller
public class Test1 {

    @RequestMapping(value = "/context", method = RequestMethod.GET)   
    public ModelAndView context() {
        return new ModelAndView("context", "command", new Context());
    }

    @RequestMapping(value = "/showUsers", method = RequestMethod.POST)
    public String showUsers(@ModelAttribute("SpringWeb")Context context, ModelMap model) {
      model.addAttribute("weather", context.getWeather());
      model.addAttribute("companions", context.getCompanions());
      return "result";
    }

}

【问题讨论】:

标签: java jquery ajax spring jsp


【解决方案1】:

第一个loadData() 函数在您的代码中不可用。

第二次使用type="button"而不是type="submit",原因如下。

对于button,当页面出现任何 javascript 错误时,除了记录错误之外,它不会做任何事情。

对于submit,无论是否发生错误都会提交页面。

<input type="button" value="Submit" onclick="loadAjax()" />

【讨论】:

  • 我做了这些改变。当我点击提交时,什么也没有发生。
  • 你的loadAjax()函数调用了吗?如果是,请检查您的浏览器控制台是否发生任何 javascript 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 2018-12-20
  • 2020-01-09
  • 2015-11-02
相关资源
最近更新 更多