2013-10-25 21 views
4

我在使用post方法調用另一個Mason組件(B.m)的Mason組件(A.m)中有一個HTML表單。我希望這個Mason組件(B.m)將值返回給Mason組件中的HTML表單(A.m)。然後我想將這個返回的值傳遞給一個Javascript函數。獲取HTML Form Post方法的返回值

我該怎麼做?我是網絡開發新手。

+0

閱讀上Ajax請求。 – amon

回答

3

您需要提出一個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頁面,幷包含您的形式,幷包含一些代碼,以指示的形式發出AJAX請求,B組分當用戶單擊「提交」按鈕,然後在結果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