2017-03-16 67 views
0

最近我一直在研究jQuery,今天我正在使用AJAX。我現在想要做的就是將日期選擇器的日期發送到返回該日期的PHP頁面。 我稍後將改進PHP頁面來完成我需要做的事情。 這裏的HTML頁面的代碼:jQuery/AJAX交互問題

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <meta name="generator" content="AlterVista - Editor HTML"/> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"> 
    $(document).ready(function() { 
     $("#foo").submit(function(){ 
      var serializedData = $(this).serialize(); 
      $.post('demo.php', serializedData, function(response) { 
       // Log the response to the console 
       console.log("Response: "+response); 
       $("#result").text() = response; 
      }); 
     }); 
    }); 
    </script> 
    <title></title> 
</head> 
<body> 
    <form id='foo'> 
     <input type='date' id='dataI' name='dataI'> 
     <input type='submit' value='send'> 
     <p id='result'></p> 
    </form> 
</body> 
</html> 

而這裏的簡單的PHP頁面我提出:

<?php 
    echo $_POST["dataS"]; 
?> 

但是,當我嘗試發送數據什麼也沒有發生。我究竟做錯了什麼?我嘗試使用我在堆棧溢出中看到的解決方案,但它不起作用。

+0

有任何數量的原因可能會失敗。檢查控制檯的網絡選項卡,看看請求的狀態是 –

回答

0

我附上代碼示例;

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta name="generator" content="AlterVista - Editor HTML"/> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
    
 
    <script type="text/javascript"> 
 
    function validate(){ 
 
\t \t 
 
\t \t var serializedData = $('#foo').serialize(); 
 
      $.post('ajax.php', serializedData, function(response) { 
 
       // Log the response to the console 
 
       console.log("Response: "+response); 
 
       $("#result").html(response); 
 
      }); 
 
return false; 
 

 
\t } 
 
    </script> 
 
    <title></title> 
 
</head> 
 
<body> 
 
    <form id='foo' action="#" onsubmit="return validate()"> 
 
     <input type='date' id='dataI' name='dataI'> 
 
     <input type='submit' value='send'> 
 
     <p id='result'></p> 
 
    </form> 
 
</body> 
 
</html>

Ajax代碼文件;

echo $_POST["dataI"]; 
+0

,並在ajax文件中正確的字段名稱,如「dataI」而不是「dataS」 –

0

嘗試添加返回false;之後

$.post('demo.php', serializedData, function(response) { 
      // Log the response to the console 
      console.log("Response: "+response); 
      $("#result").text() = response; 
     }); 

聲明。

$(document).ready(function() { 
     $("#foo").submit(function(){ 
      var serializedData = $(this).serialize(); 
      $.post('demo.php', serializedData, function(response) { 
       // Log the response to the console 
       console.log("Response: "+response); 
       $("#result").text() = response; 
      }); 
      return false; 
      }); 
     });