javascript - 获取 HTML 表单 Post 方法的返回值

标签 javascript html perl mason

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

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

最佳答案

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

这是 Mason 中的一个小例子,它当然非常简单,您应该添加一些错误检查和一些转义,但我认为这可能是一个好的开始。您的 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

关于javascript - 获取 HTML 表单 Post 方法的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19600596/

相关文章:

windows - 如何在后台运行 .exe,使用 perl PAR 的 pp 模块从 perl 脚本创建

javascript - 为什么我的 for 循环卡在第二个选项上?

javascript - 为什么结果字符串只返回最后一个结果值

html - 空 div(样式为 : height as percentage) will not display

android - 加载 Android 后获取 WebView 内容高度

html - 有什么方法可以使边框更接近正文内容? (HTML/CSS) 图片提供

javascript - (Grid js) 我希望搜索按钮在右侧,添加按钮在左侧,我该怎么办?

javascript - 创建组件时如何以及在何处将 JSON 数据作为 prop 传递

mysql - 在 Perl 中使用 CSV 更新 MYSQL 数据库?

mysql - 转义拉丁字符以使用 perl 插入和获取数据库