PHP 代码:点击按钮提交 POST 请求到指定网站
您可以使用 cURL 库或 fetch 函数来向指定的 PHP 网站发送 POST 请求。以下分别是两种方法的示例代码:
使用 cURL 库
// 设置 POST 请求的 URL 和参数
$url = 'http://example.com/post.php';
$data = array('param1' => 'value1', 'param2' => 'value2');
// 初始化 cURL
$ch = curl_init();
// 设置 cURL 选项
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 执行 cURL 请求
$response = curl_exec($ch);
// 关闭 cURL
curl_close($ch);
// 处理响应
echo $response;
使用 fetch 函数
<button onclick="sendPostRequest()">提交 POST 请求</button>
<script>
function sendPostRequest() {
// 设置 POST 请求的 URL 和参数
var url = 'http://example.com/post.php';
var data = {param1: 'value1', param2: 'value2'};
// 发送 POST 请求
fetch(url, {
method: 'POST',
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
}
</script>
在您的 HTML 页面中,您可以将这些代码放在一个 JavaScript 函数中,并在按钮被点击时调用这个函数。使用 cURL 库发送请求后,您可以处理返回的响应。使用 fetch 函数发送请求后,您可以使用 .then() 方法处理成功响应,使用 .catch() 方法处理错误响应。
请注意,这些示例代码需要根据您的具体需求进行调整。例如,您可能需要更改 POST 请求的 URL 和参数,以及处理响应的方式。
原文地址: https://www.cveoy.top/t/topic/mmzR 著作权归作者所有。请勿转载和采集!