2015-11-05 77 views
1

我正在編寫一個基本的AJAX應用程序,需要通過POST發送一些數據到一個php頁面。AJAX不能正確發送POST變量

我在這裏得到的問題是,PHP頁面沒有正確接收$ _POST中的數據:如果我嘗試打印其內容,我得到一個空數組。

你能幫我指出問題嗎?

// global variables 
var sendReq = getXmlHttpRequestObject(); 


// get the browser dependent XMLHttpRequest object 
function getXmlHttpRequestObject() { 
    if (window.XMLHttpRequest) { 
     return new XMLHttpRequest(); 
    } 
    else if(window.ActiveXObject) { 
     return new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    else { 
     document.getElementById('status').innerHTML = 
     'Status: Error while creating XmlHttpRequest Object.'; 
    } 
} 

// send a new message to the server 
function sendMessage() { 
    if (receiveReq.readyState == 0 || receiveReq.readyState == 4) { 
     sendReq.open("POST", 'chatServer.php', true); 
     sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 

     // bind function call when state change 
     sendReq.onreadystatechange = messageSent; 

     var param = "message=ciao"; 
     sendReq.send(param); 

     // reset the content of input 
     document.getElementById("message").value = ""; 
    } 
} 

chatServer.php

<?php session_start(); 
// send headers to prevent caching 
header("Expires: Mon, 1 Jul 2000 08:00:00 GMT"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT"); 
header("Cache-Control: no-cache, must-revalidate"); 
header("Pragma: no-cache"); 

// open database 
$file_db = new PDO('sqlite:chatdb.sqlite') or die("cannot open database"); 

if ($file_db) { 
    print_r($_POST); // this prints an empty array!!! 

    // check if a message was sent to the server 
    if (isset($_POST["message"]) && $_POST["message"] != '') { 
     $message = $_POST["message"]; 
     // do stuff 
    } 
} 


?> 

編輯:

更新功能,仍然沒有工作

function sendMessage() { 
    if(sendReq){ 
     /* set the listener now for the response */ 
     sendReq.onreadystatechange=function(){ 
      /* Check for the request Object's status */ 
      if(sendReq.readyState==4) { 
       if(sendReq.status==200){ 
        /* Process response here */ 
        clearInterval(timer); 
        getUnreadMessages(); 
       } 
      } 
     }; 

     /* Open & send request, outwith the listener */ 
     sendReq.open("POST", 'chatServer.php', true); 
     sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 

     var param = 'message=ciao'; 
     sendReq.send(param); 
     document.getElementById("message").value = ""; 
     // relocate to php page for debugging purposes 
     window.location.replace("chatServer.php"); 
    } 
} 
+0

通過使用'window.location的.replace'你發送請求,但不要等待答案 - 相反,你加載php腳本 - 這是行不通的。使用控制檯查看ajax請求中發生了什麼。 – RamRaider

+0

謝謝,那正是發生了什麼事。 POST正在工作,但我正在以錯誤的方式進行測試。 – Ivano

回答

1

sendMessage功能是不完全正確 - 看看這看看它是否有幫助。

在最初檢查的receiveReq狀態不參照實例化XMLHttpRequest對象sendReq功能 - 也,請求絕不會因爲opensend電話是代碼內發送,即使它已經使用sendReq檢查響應的塊...

var sendReq = getXmlHttpRequestObject(); 

function messageSent(response){ 
    console.info(response); 
} 

function getXmlHttpRequestObject() { 
    if (window.XMLHttpRequest) { 
     return new XMLHttpRequest(); 
    } else if(window.ActiveXObject) { 
     return new ActiveXObject("Microsoft.XMLHTTP"); 
    } else { 
     document.getElementById('status').innerHTML = 'Status: Error while creating XmlHttpRequest Object.'; 
    } 
} 

/* 
    Set the `param` as a parameter to the function, can reuse it more easily. 
*/ 

function sendMessage(param) { 
    if(sendReq){ 
     /* set the listener now for the response */ 
     sendReq.onreadystatechange=function(){ 
      /* Check for the request Object's status */ 
      if(sendReq.readyState==4) { 
       if(sendReq.status==200){ 
        /* Process response here */ 
        messageSent.call(this, sendReq.response); 
       } else { 
        /* there was an error */ 
       } 
      } 
     }; 

     /* Open & send request, outwith the listener */ 
     sendReq.open("POST", 'chatServer.php', true); 
     sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 

     sendReq.send(param); 
     document.getElementById("message").value = ""; 
    } 
} 

/* send some messages */ 
sendMessage('message=ciao'); 
sendMessage('message=ajax...sent via POST'); 

最初錯過了param var聲明,所以糾正了這個錯誤。

更新

chatserver.php (example) 
------------------------ 
<?php 
    /* 
     demo_chatserver.php 
    */ 
    session_start(); 

    if($_SERVER['REQUEST_METHOD']=='POST'){ 
     /* 
      include your db connection 
      set your headers 
     */ 



     if(isset($_POST['message']) && !empty($_POST['message'])){ 
      @ob_clean(); 

      /* Create the db conn && test that it is OK */ 

      /* for the purposes of the tests only */ 
      $_POST['date']=date(DATE_COOKIE); 
      echo json_encode($_POST, JSON_FORCE_OBJECT); 
      exit(); 
     } 
    } 
?> 



html/php page 
--------------- 
<!doctype html> 
    <html> 
    <head> 
     <title>ajax tests</title> 
     <script type='text/javascript'> 
      var sendReq = getXmlHttpRequestObject(); 
      function messageSent(response){ 
       console.info('This is the response from your PHP script: %s',response); 
       if(document.getElementById("message")) document.getElementById("message").innerHTML=response; 
      } 
      function getXmlHttpRequestObject() { 
       if (window.XMLHttpRequest) { 
        return new XMLHttpRequest(); 
       } else if(window.ActiveXObject) { 
        return new ActiveXObject("Microsoft.XMLHTTP"); 
       } else { 
        document.getElementById('status').innerHTML = 'Status: Error while creating XmlHttpRequest Object.'; 
       } 
      } 
      /* 
       Set the `param` as a parameter to the function, can reuse it more easily. 
      */ 
      function sendMessage(param) { 
       if(sendReq){ 
        /* set the listener now for the response */ 
        sendReq.onreadystatechange=function(){ 
         /* Check for the request Object's status */ 
         if(sendReq.readyState==4) { 
          if(sendReq.status==200){ 
           /* Process response here */ 
           messageSent.call(this, sendReq.response); 
          } else { 
           /* there was an error */ 
          } 
         } 
        }; 
        /* Open & send request, outwith the listener */ 

        /*NOTE: I have this in a folder called `test`, hence the path below!! */ 
        sendReq.open("POST", '/test/demo_chatserver.php', true); 
        sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
        sendReq.send(param); 
        if(document.getElementById("message")) document.getElementById("message").innerHTML = ""; 
       } 
      } 
      /* send some data - including original 'message=ciao' but other junk too */ 
      window.onload=function(event){ 
       sendMessage('message=ciao&id=23&banana=yellow&php=fun&method=post&evt='+event); 
      } 
     </script> 
    </head> 
    <body> 
     <output id='message' style='display:block;width:80%;float:none;margin:5rem auto;padding:1rem;box-sizing:content-box;border:1px solid black;'> 
      <!-- 
       Expect to see content appear here.... 
      --> 
     </output> 
    </body> 
</html> 


Should output something like:- 
------------------------------ 
{"message":"ciao","id":"23","banana":"yellow","php":"fun","method":"post","evt":"[object Event]","time":1446730182,"date":"Thursday, 05-Nov-15 13:29:42 GMT"} 
+0

好奇關於downvote,請求得到發送,它已經糾正了OP的問題......沒關係 - 仇敵會討厭 – RamRaider

+0

你可能已經downvoted,因爲你應該解釋爲什麼你的解決方案的工作原理和你做了什麼。 –

+0

謝謝你的回答。 除了錯字,我還修改了我的函數結構來匹配你的結構,謝謝你的解釋。 問題是,它仍然不工作,我的PHP頁面無法正確接收$ _POST變量。 我正在更新操作,讓你看看我更新的代碼 – Ivano

1

在這裏,我會告訴我如何發送/接收基本的CRUD(創建,讀取,刪除,更新)的應用程序,你可以在你的代碼中實現Ajax請求。

所有簡單的形式與HTML

<form action="controller.php" method="POST"> 
    <input type="text" class="form-control" name="userName"/> 
    <input type="text" class="form-control" name="password"/> 
    <input type="Submit" value="Log In" onclick="logIn(); return false;"/> 
</form> 

輸入元件之後的首先我們編寫使用FORMDATA對象,並使用AJAX技術發送請求JavaScript函數:

function logIn() 
{ 
    //Creating formData object 
    var formData = new FormData(); 
    //Getting input elements by their classNames 
    var formElements = document.getElementsByClassName("form-control"); 
    //Append form elements to formData object 
    for(var i = 0; i < formElements.length; i++) 
     formData.append(formElements[i].name, formElements[i].value) 
    //Creating XMLHttpRequest Object 
    var xmlHttp = new XMLHttpRequest(); 
     xmlHttp.onreadystatechange = function() 
     { 
      if(xmlHttp.readyState == 4 && xmlHttp.status == 200) 
      { 
       alert(xmlHttp.responseText); 
      } 
     } 
     xmlHttp.open("POST", "controller.php"); 
     xmlHttp.send(formData); 
}