2017-08-13 247 views
0

正如標題所述,我正在尋找使用JavaScript進行POST請求,並且得到響應。這裏是我當前的代碼:AJAX POST請求與響應

var request = new XMLHttpRequest(); 
request.open('POST', 'test.php', true); 

request.onload = function() { 
    if (request.status >= 200 && request.status < 400) { 
    // Success 
    console.log(request.responseText) 
    } else { 
    // Server-side Error 
    console.log("Server-side Error") 
    } 
}; 

request.onerror = function() { 
    // Connection Error 
    console.log("Connection Error") 
}; 

request.send({ 
    'color':'red', 
    'food': 'carrot', 
    'animal': 'crow' 
}); 

隨着test.php的幸福:

<?php 
    echo $_POST['color']; 
?> 

這應返回 '紅',而是返回任何內容。

這似乎是一個簡單的問題,但我只能找到使用jQuery的人的解決方案。我想要一個不依賴於庫的解決方案。

+0

**危險**:此代碼[易受XSS影響](https://www.owasp.org/index.php/XSS)用戶輸入在插入HTML文檔之前需要轉義! – Quentin

+0

**警告**:可以通過查詢字符串,發佈數據或cookie填充'$ _REQUEST'。命名衝突(特別是涉及cookie時)可能會導致混淆。最好避免使用更明確的superglobals'$ _COOKIES','$ _POST'和'$ _GET'。 – Quentin

+0

是的,我知道這很容易受到XSS的影響 - 我很快把它放在一起,因爲我不想上傳我的真實代碼。 – 073148974301870437087

回答

0

send方法接受一個字符串,而不是一個對象,也許更像是:

var request = new XMLHttpRequest(); 
request.onload = function() { 
    if (request.status >= 200 && request.status < 400) { 
    console.log(request.response) 
    } else { 
    console.log("Server-side Error") 
    } 
}; 

request.onerror = function() { 
    console.log("Connection Error") 
}; 

request.open('POST', 'test.php', true); 
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); 
request.send('color=red&food=carrot&animal=crow'); 
+0

呵呵。我認爲這會起作用,但它仍然沒有給我什麼。 – 073148974301870437087

+0

這使得請求內容類型爲「text/plain」,因此PHP不知道如何對其進行解碼,並且未填充「$ _REQUEST」。您可以手動設置Content-Type,但FormData是一種更好的方法。 – Quentin

+0

好點@Quentin〜測試過,發現沒有反應...添加標題 - 繁榮! – RamRaider

0

JavaScript的問題

您正試圖發送一個通用的對象,因此它被轉換爲字符串( "[Object object]"),數據丟失。

改爲將數據轉換爲FormData對象。

var data = { 
    'color':'red', 
    'food': 'carrot', 
    'animal': 'crow' 
}; 

var formData = new FormData(); 

Object.keys(data).forEach(function (key) { 
    formData.append(key, data[key]); 
}) 

request.send(formData); 

PHP的問題

目前所有的解決方案的簡單的「test.php的」源代碼登錄,而不是記錄「紅色」到控制檯

控制檯

這是與您的代碼無關的問題。這也是一個常見問題。請參閱:PHP code is not being executed, instead code shows on the page

+0

這只是記錄我輸入到控制檯的源代碼... – 073148974301870437087

+0

@ 073148974301870437087 - 當我測試它時,它完美運行:http://i.imgur.com/qFAdiU7.png – Quentin

+0

http://imgur.com/a/bLWpZ – 073148974301870437087