2015-09-05 32 views
1

我需要此問題的幫助,請幫助我。如何在PHP中接收Ajax urlencode

我正在嘗試向PHP發送Ajax urlencode,但是當HTML直接發送到PHP時,PHP不會顯示POST內容。

我在Ajax中使用此代碼發送FormData到PHP。

有了這個簡單的PHP代碼,看看是否在PHP文件名的作品: 「thefile.php」

有了這個JS,HTML和PHP代碼:

function sendme() { 
    var form = new FormData(document.forms['form']); 
    if (window.XMLHttpRequest) 
    var ajax = new XMLHttpRequest(); 
    else 
    var ajax = new ActiveXObject("Microsoft.XMLHTTP"); 
    ajax.open("post", "thefile.php", true); 
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); 
    ajax.onreadystatechange = function() { 
    if (ajax.readyState == 4 && ajax.status == 200) 
     console.log(ajax.responseText); //to see the return on in console 
    }; 
    ajax.send(form); 
}; 
<form name="form" onsubmit="return false;"> 
    <input type="text" name="user" required autofocus/> 
    <input type="password" name="pass" required/> 
    <input type="submit" name="send" onclick="sendme();" /> 
</form> 
<?php 
    print_r($_POST); //to see $_POST Array Content 
    echo ' '.$_POST['user'].' '.$_POST['pass']; 
?> 

的輸入內容: 用戶:用戶名 通過:密碼

結果:

Array 
(
[------WebKitFormBoundary50040KVnXutLwSAd 
Content-Disposition:_form-data;_name]=>"user" 

username 
[------WebKitFormBoundary50040KVnXutLwSAd 
Content-Disposition:_form-data; name]=>"pass" 

password 
------WebKitFormBoundary50040KVnXutLwSAd-- 
) 

Notice: Undefined index: user in thefile.php on line 3 
Notice: Undefined index: pass in thefile.php on line 3 
+0

希望這有助於你。 [一](http://stackoverflow.com/questions/18906547/how-to-ajax-post-to-php),[two](http://stackoverflow.com/questions/9001526/send-array-with -ajax-to-php-script),[三](http://stackoverflow.com/questions/5004233/jquery-ajax-post-example-with-php)。 –

回答

0

好像你的HTTPHeader 「應用程序/ x-WWW的形式,進行了urlencoded」 不與FORMDATA對象兼容。

只是註釋掉象下面這樣:

ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); 

to 

//ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); 

如果您更喜歡使用 「應用程序/ x-WWW窗體-urlencoded;字符集= UTF-8」,在您的要求。你必須編寫簡單的JavaScript代碼,使其作爲普通的字符串,如:

var form = "user=root&pass=root"; 
..... 
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); 
..... 
ajax.send(form); 
1

the specification

FORMDATA:按運行multipart/form-data編碼算法,以對象作爲表單數據的結果設置並以utf-8作爲顯式字符編碼進行流式處理。

您正在生成multipart/form-data主體,但您明確設置內容類型標頭聲稱它是application/x-www-form-urlencoded; charset=UTF-8

或者:

  • 指定正確的內容類型
  • 不指定內容類型,讓XHR設置爲你