【问题标题】:Not able to use ajax in spring mvc form无法在 spring mvc 表单中使用 ajax
【发布时间】:2013-03-17 00:23:06
【问题描述】:

我正在尝试在 spring mvc 中以表单形式实现基于 ajax 的帖子。

这是我的代码:

<form:form method="POST" commandName="emailDomain">
    <form:textarea path="emailText" rows="5" id="emailList"
        placeholder="Write emails to submit us, saperated by ';'"
        style="width: 100%" />

<form:select items="${categoryMap}" path="categoryId" id="categoryList"
    onchange="showEmails()" />

    <br />
    <p align="center">
        <button type="button" value="Submit" id="submitEmails">Submit emails</button>
    </p>
    <p align="center" class="text-info">${var}</p>
</form:form>

我的ajax代码是:

<script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>

     <script type="text/javascript">
     function showEmails() {

            var categoryId = $('#categoryList').val();
    var emailText = $('#emailList').val();

    $.ajax({
        type : "POST",
        url : "http://localhost:8081/chatbooster/forms/email.html?cat=1",
                data : "categoryId=" + categoryId + "&emailText=" + emailText,
        success : function(response) {


        },
        error:function (xhRequest, ErrorText, thrownError) {
            alert('Error: '  + '  ' + thrownError);
        }
    });
}

问题是点击按钮后,它显示错误作为警报,但没有任何解释。之后它会跳转到显示 json 响应的页面。如果我根本不使用弹簧形式标签,该代码将起作用。它不会显示任何错误,也不会显示 json 响应,但同样,我将无法从数据库中填充选择下拉列表。

我的控制器是:

@Controller
  @RequestMapping(value = "/email.html")
  public class EmailController{

    @RequestMapping(method = RequestMethod.GET)
      public String showForm(Model model,
          @RequestParam(value = "cat", required = true) String category,
          HttpServletRequest request, HttpServletResponse response) {
        clearSession(request, response);

        return "email";
      }

    @RequestMapping(value = "/submitemails", method = RequestMethod.GET)
      public @ResponseBody
      String submitAndRefreshEmails() {
        System.out.println("check");

        return "email";
      }

    @RequestMapping(method = RequestMethod.POST)
      public @ResponseBody
      EmailJsonResponse addEmail(@Valid EmailDomain emailDomain,
          BindingResult result,
          @RequestParam(value = "cat", required = true) String category,
          HttpServletRequest request, HttpServletResponse response)
      throws Exception {

        //return emailjsonresponse object, a simple object carrying few ints and strings

      }

    @ModelAttribute("categoryMap")
      public Map<Long, String> populateCategoryList(
          @RequestParam(value = "cat", required = true) String category)
      throws Exception {

        // populating drop down 

      }

  }

我已经阅读了很多关于此的讨论,但我不知道如何使它成为这样的情况?任何人都可以在这里帮助我吗?我指的是这个例子http://www.javacodegeeks.com/2012/02/spring-mvc-and-jquery-for-ajax-form.html

编辑 1:

我什至尝试过这个新的:

<script type="text/javascript">
  $(document).ready(function() {
      $('#submitEmails').onclick(function() {
          $.getJSON('http://localhost:8081/chatbooster/forms/submitemails.html?cat=1',
                {
                    categoryId : $('#categoryList').val(),
                    emailText : $('#emailList').val(),
                    ajax : 'true'
                }, 
                function(data) {
                    alert('data found');
                }
          );
      });
  });

但我仍然显示 json 响应。我无法理解为什么会这样?我试过这个http://rockhoppertech.com/blog/spring-mvc-3-cascading-selects-using-jquery/。当我不使用弹簧表单组件时,我能够实现 ajax。但这会给我从数据库中填充下拉元素带来麻烦。我缺少一些东西。有什么想法吗?

编辑 2

现在我明白了这个问题的原因。正是我提交的表单最终导致我收到 json 响应。我需要做的是从按钮调用jquery函数,使按钮类型的提交按钮而不是提交类型。单击该按钮将调用与控制器的 GET 请求类型相关的方法。但为此,我需要在单击提交按钮时调用 submitAndRefreshEmails 方法。谁能告诉我该怎么做?当控制器中有很多GET类型的方法时,如何调用特定的GET类型方法?

【问题讨论】:

  • 包含这个的页面是否也是从http://localhost:8081/加载的?否则,您的请求将违反 SOP。尝试设置crossDomain 参数。
  • @vlad halmer 在您的 ajax 调用中,我没有看到 data 被提交?看起来您的 addEmail 方法需要一个有效的 EmailDomain 对象...
  • @user1766760 正如你所说,我在我的 ajax 调用中添加了数据:“categoryId=" + categoryId + "&emailText=" + emailText。因此,控制器能够从视图中获取数据,但在提交表单后,页面会显示 json 响应。我已经在视图页面中编辑了 ajax 调用。
  • @CBrow 是的,页面在 localhost 中运行。我正在调用 localhost url 来调用其各自的控制器。我无法理解 crossDomain 参数。您能告诉我有关它的基本信息或任何链接吗?你的意思是这样的吗stackoverflow.com/questions/11377994/…
  • 在 MVC 端,您需要一个映射到某个 URL 的 Controller 方法,该 URL 将返回您的 submitAndRefreshEmails 方法。然后你只需使用映射的 URL 来调用它。

标签: jquery ajax json spring-mvc


【解决方案1】:

由于您正在执行 AJAX 调用,因此您希望在不(重新)加载 HTML 页面的情况下返回信息的 sn-p(您的 JSON 数据)。因此使用@ResponseBody。

如果 AJAX 调用绑定到表单提交,它将触发页面加载(我似乎无法找到解释这一点的好来源)。因此,您需要停止默认行为。

$form.bind('submit', function(e) {
    $.post('epdReviewSaveChanges.json', mData, function(response) {
            //do stuff...
    }

    e.preventDefault();
    return false;
});

上面的一点解释,取自here。

e.preventDefault() 部分代码阻止浏览器执行默认操作。 return false; 更进一步,因为它还阻止了该事件传播(或“冒泡”)DOM。

我怀疑您最初遇到的问题与如何使用 AJAX 调用/Spring 有关。我不是在谈论任何跨域问题,这可能需要额外/不同的解决方案。

问题2至于映射到控制器内的特定方法,您可以使用value来区分不同的调用。例如:

@RequestMapping(value="/Upload.html",method = RequestMethod.POST)

【讨论】:

  • 感谢您的回复...我没有使用 preventDefault 来解决我的问题,但是是的,我已将不同的值映射到返回 Json 响应的方法,并且该方法在不同的控制器中定义。
猜你喜欢
  • 1970-01-01
  • 2021-07-09
  • 2016-07-14
  • 1970-01-01
  • 2011-12-04
  • 1970-01-01
  • 2018-04-03
  • 2016-03-14
  • 1970-01-01
相关资源
最近更新 更多