我在 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>.
结果是这样的:
关于javascript - 获取 HTML 表单 Post 方法的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19600596/