[英]Can an XMLHTTPRequest capture form data, and be sent to a PHP cURL request to be posted?
我有一個 javascript 文件,它捕獲表單輸入,使用輸入發出 XMLHTTP POST 請求,並處理錯誤。 我目前正在發布到單獨的 PHP 文件,因為請求需要敏感的 API 數據並且需要編碼。 然后,我從 PHP 文件發送 cURL 請求以將表單輸入發布到遠程 URL。
我想根據 cURL 響應來處理錯誤,但是 XHR 錯誤是不同的,並且優先於 cURL 錯誤。 這兩個請求都是必要的,還是我應該只發出一個 XHR 或 cURL 請求?
是否需要這兩個請求取決於您的用例。 既然你的聽起來確實是必要的,那絕對沒有錯。
如何在客戶端處理服務器端錯誤也完全取決於您。 例如,讓我們假設這個非常基本的 XHR 處理程序,它將一些 JSON 數據發送到某個端點並評估響應:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/endpoint.php');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = () => {
const status = xhr.status;
const response = JSON.parse(xhr.responseText);
if (status == 200) {
// Everything's fine
console.log(response.data);
} else {
// Some error occured
console.log(status, response.data);
}
};
xhr.send(JSON.stringify({}));
索引.html
上面的錯誤處理策略圍繞着從服務器接收到的 HTTP 狀態碼,所以我們需要確保它們是根據我們的需要發送的:
/**
* In case an error occurred, send an error response.
*/
function error(string $message) {
// For properly returning a JSON response, see:
// https://stackoverflow.com/a/62834046/3323348
header("Content-type: application/json; charset=utf-8");
http_response_code(400); // HTTP status code - set to whatever code's appropriate
echo json_encode(['data' => $message]);
}
/**
* Send a response denoting a success.
*/
function success(array $data) {
// For properly returning a JSON response, see:
// https://stackoverflow.com/a/62834046/3323348
header("Content-type: application/json; charset=utf-8");
http_response_code(200);
echo json_encode(['data' => $data]);
}
// For proper error checking on JSON data, see:
// https://stackoverflow.com/a/37847337/3323348
$data = json_decode(file_get_contents('php://input'), true);
// Assume some processing happened. That result is either
// a success, or an error.
$success = mt_rand(0,1);
$success ? success($data) : error('An error occured.');
端點.php
關於 cURL,您可以輕松地將最后兩行更改為例如:
if(curl_errno($ch)) { // Assuming $ch is your cURL handle
error('Curl error: '.curl_error($ch));
}
else {
success($data);
}
或者您調整錯誤 function - 如果它接受數組而不是簡單字符串,您將能夠將更復雜的錯誤數據返回給您的 JavaScript 客戶端:
$curl_error = curl_errno($ch);
if ($curl_error) {
error([
'type' => 'cURL',
'no' => curl_errno($ch),
'message' => curl_error($ch)
]);
}
不過,您不必堅持使用狀態代碼來處理錯誤。 您可以發回 JSON object,其中一個鍵表示一些成功收集的數據,如果發生錯誤,一個鍵表示錯誤。 或者任何適合您的需求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.