获取HTML Form Post方法的返回值

时间:2013-10-25 22:50:34

标签: javascript html perl mason

我在Mason组件(A.m)中有一个HTML表单,它使用post方法调用另一个Mason组件(B.m)。我希望这个Mason组件(B.m)将值返回到Mason组件(A.m)中的HTML表单。然后我想将此返回值传递给Javascript函数。

我该怎么做?我是网络开发的新手。

1 个答案:

答案 0 :(得分:5)

您需要发出AJAX请求。虽然不是绝对必要,但我建议您使用jQuery,这会让事情变得更容易。另请查看此问题:jQuery AJAX submit form

这是梅森的一个小例子,它当然非常简化,你应该添加一些错误检查和一些转义,但我认为这可能是一个好的开始。您的A.mc组件可能如下所示:

<html>
<head>
  <title>This is A</title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  <script>
  $(document).ready(function() {

    $("#myform").submit(function() { // intercepts the submit event
      $.ajax({ // make an AJAX request
        type: "POST",
        url: "B", // it's the URL of your component B
        data: $("#myform").serialize(), // serializes the form's elements
        success: function(data)
        {
          // show the data you got from B in result div
          $("#result").html(data);
        }
      });
      e.preventDefault(); // avoid to execute the actual submit of the form
    });

  });
  </script>
</head>
<body>
  <form id="myform">
  <input type="text" name="mytext" />
  <input type="submit" />
  </form>

  <div id="result"></div>
</body>
</html>

它只是一个加载jQuery库并包含表单的HTML页面,它包含一些代码,用于指示表单在用户单击“提交”按钮时向B组件发出AJAX请求,然后显示返回的内容结果div中的B组件。

这可能是您的B.mc组件:

<%class>
  has 'mytext';
</%class>
I got this text <strong><% $.mytext %></strong> from your form,
and its length is <strong><% length($.mytext) %></strong>.

结果将如下:

enter image description here