2011-09-13 67 views
4

我不知道如何獲取「Hello World!」在PHP中用於以下Javascript代碼。
我知道我可以使用$ _POST ['']如果內容類型是「application/x-www-form-urlencoded」,但不適用於「text/plain」。在php中,如何獲取XMLHttpRequest的send()方法的text/plain值

var xhr = new XMLHttpRequest(); 
xhr.open('POST', 'example.php', true); 
xhr.setRequestHeader('Content-Type', 'text/plain'); 
xhr.send('Hello World!'); 

回答

4

有許多事情錯了你的請求。您可以使用’ t POST數據,而不使用application/x-www-form-urlencoded。其次,「 Hello World! 」不會被轉義或附加到變量。

以下是將數據發送到服務器的JavaScript代碼。

var xhr = new XMLHttpRequest(); 
var params = 'x='+encodeURIComponent("Hello World!"); 
xhr.open("POST", 'example.php', true); 
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
xhr.setRequestHeader("Content-length", params.length); 
xhr.setRequestHeader("Connection", "close"); 
xhr.onreadystatechange = function() { 
    if(xhr.readyState == 4 && xhr.status == 200) { 
     alert(xhr.responseText); 
    } 
} 
xhr.send(params); 

您可以通過PHP中的$_POST['x']訪問此項。

或者,您可以使用$_GET['x']通過使用下面的代碼。

var xhr = new XMLHttpRequest(); 
var params = encodeURIComponent("Hello World!"); 
xhr.open("GET", 'example.php?x='+params, true); 
xhr.onreadystatechange = function() { 
    if(xhr.readyState == 4 && xhr.status == 200) { 
     alert(xhr.responseText); 
    } 
} 
xhr.send(null); 

GET更符合使用Content-type: text/plain的想法。

+0

這是我想知道的所有:)謝謝 – abc

+1

@genkidesu:我看到你是新來的。本網站習慣於接受您認爲有用的答案。否則,人們會更不願意回答您可能會遇到的任何問題。 – Herbert

+0

@abc您應該標記爲接受Herbert的回覆。赫伯特你好,謝謝你正確的聲明,我試圖沒有成功的[w3school](https://www.w3schools.com/js/tryit.asp?filename=tryjs_ajax_post2),與你的相比,他們一看起來混亂和不完整(我想知道它是如何工作的) – Robert

7

這PHP將讀取請求主體的原始數據:

$data = file_get_contents('php://input'); 

線路3:

xhr.setRequestHeader('Content-Type', 'text/plain'); 

不需要作爲張貼/純文本將內容類型設置爲文本純;字符集= UTF-8
http://www.w3.org/TR/XMLHttpRequest/#the-send-method

+0

儘管我同意「正確」的標準做法是始終格式化表單數據,但「php:// input」位是一個值得注意的有趣的細節。有關它的更多信息可以在網絡搜索中找到:[link](http://www.google.com/search?q=「php:// input」) –

+0

將POST數據發送爲純文本?我從來沒有讀過HTTP標準要求POST數據是「application/x-www-form-urlencoded」,例如PHP和瀏覽器使用該應用程序來通信比HTTP更高的一級 – fishbone

相關問題