简体   繁体   English

XMLHTTPRequest 是否可以捕获表单数据,并发送到 PHP cURL 请求发布?

[英]Can an XMLHTTPRequest capture form data, and be sent to a PHP cURL request to be posted?

I have a javascript file that captures form input, makes an XMLHTTP POST request with the input, and handles errors.我有一个 javascript 文件,它捕获表单输入,使用输入发出 XMLHTTP POST 请求,并处理错误。 I am currently POSTing to a separate PHP file, as the request requires sensitive API data and needs encoding.我目前正在发布到单独的 PHP 文件,因为请求需要敏感的 API 数据并且需要编码。 From the PHP file, I then send a cURL request to post the form input to the remote URL.然后,我从 PHP 文件发送 cURL 请求以将表单输入发布到远程 URL。

I want to handle errors based on the cURL response, but the XHR errors are different and take precedent over the cURL errors.我想根据 cURL 响应来处理错误,但是 XHR 错误是不同的,并且优先于 cURL 错误。 Are both these requests necessary, or should I only be making either a single XHR or cURL request?这两个请求都是必要的,还是我应该只发出一个 XHR 或 cURL 请求?

Whether or not both requests are necessary depends on your use case.是否需要这两个请求取决于您的用例。 Since yours sounds as they are indeed necessary, there's absolutely nothing wrong with it.既然你的听起来确实是必要的,那绝对没有错。

How you handle server-side errors client-side is also entirely up to you.如何在客户端处理服务器端错误也完全取决于您。 For example, let's assume this pretty basic XHR handler, which sends some JSON data off to some endpoint and evaluates the response:例如,让我们假设这个非常基本的 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({}));

index.html索引.html

The above error handling strategy revolves around the HTTP status code received from the server, so we'll need to make sure they're send according to our needs:上面的错误处理策略围绕着从服务器接收到的 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.');

endpoint.php端点.php

Regarding cURL, you could easily change the last two lines to eg:关于 cURL,您可以轻松地将最后两行更改为例如:

if(curl_errno($ch)) { // Assuming $ch is your cURL handle

    error('Curl error: '.curl_error($ch));
}
else {

    success($data);
}

Or you adapt the error function - if it would accept an array instead of a simple string, you'd be able to return more complex error data to your JavaScript client:或者您调整错误 function - 如果它接受数组而不是简单字符串,您将能够将更复杂的错误数据返回给您的 JavaScript 客户端:

$curl_error = curl_errno($ch);

if ($curl_error) {

    error([

        'type' => 'cURL', 
        'no' => curl_errno($ch), 
        'message' => curl_error($ch)
    ]);
}

You don't have to stick with status codes for your error handling, though.不过,您不必坚持使用状态代码来处理错误。 You could send a JSON object back with one key denoting some successfully collected data, and one denoting an error if an error occurred.您可以发回 JSON object,其中一个键表示一些成功收集的数据,如果发生错误,一个键表示错误。 Or whatever suits your needs.或者任何适合您的需求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM