簡體   English   中英

如何提交表單而不刷新頁面

[英]how to submit the form without refreshing the page

這是我的html代碼,當我單擊“提交”按鈕時,它顯示警報,然后當我打開retrieveform.php時,它沒有向我顯示該值,請解決這個問題

   <html>
   <head>
   <script type="text/javascript" src="jquery.js"></script>
   <script>
    $(function () {

    $('form').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'retrieveform.php',
        data: $('form').serialize(),
        success: function () {
          alert('helllo');
        }
      });

    });

  });
 </script>
 </head>
 <body>
 <form>
 <input type="text"name="t1">
 <input type="submit"name="s1"value="submit">
 </form>
 </body>
 </html>

和我的reformform.php是

 <?php
 if($_POST['t1'])
 {
 echo $_POST['t1'];
 }
 else
 {
 echo "hekllojjio";
 }
 ?>

元素“ t1”是否存在,因為它是表單的一部分,但是可能是空字符還是空字符..也許檢查是否是這種情況?

<?php
    if($_POST['t1'] && !empty($_POST['t1'])) {
        echo "You submitted t1 of: ".$_POST['t1'];
    } else {
        echo "t1 is empty";
    }
?>

還要注意的是,您可能想使用諸如Firebug之類的東西來查看加載的Ajax頁面及其結果。 除非您將響應的內容設置到頁面中,否則加載的ajax頁面上的echo語句將不會顯示在父頁面上:

<html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script type="text/javascript">
            $(function () {
                $('.form').on('submit', function (e) {
                    tValue = $(this).find(input[type=text]:first).val();
                    e.preventDefault();
                    $.ajax({
                        type: 'post',
                        url: 'retrieveform.php',
                        data: $('form').serialize(),
                        success: function (response) {
                            alert('helllo');
                            $('#placeholder').html(response);
                            $('#placeholder2').html(tValue);
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <?PHP for ($i = 1; $i <= 10; $i++) { ?>
        <form class="form" name="form_<?PHP echo $i; ?>" id="form_<?PHP echo $i;?>">
            <input type="text" id="t<?PHP echo $i; ?>" name="t<?PHP echo $i; ?>">
            <input type="submit" name="s<?PHP echo $i; ?>" value="submit">
        </form>
        <?PHP } ?>
        <div id="placeholder"></div>
        <div id="placeholder2"></div>
    </body>
</html>

這樣,您的ajax加載頁面的回顯將放在“占位符” div中的頁面上。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM