[英]Ajax request to send CURL request
I am submitting the data from a from via Ajax and it needs to make a curl request to an endpoint.我正在通过 Ajax 从 from 提交数据,它需要向端点发出 curl 请求。 I am not getting any errors but when I check the data in the endpoint it isn't there.我没有收到任何错误,但是当我检查端点中的数据时,它不存在。 If I submit the form just using normal html then it works.如果我只使用普通的 html 提交表单,那么它就可以工作。 So, something is incorrect with my CURL code I would imagine.因此,我认为我的 CURL 代码有些不正确。
<?php
$response = [];
$message = '';
$data = [
'first_name' => $_POST['first_name'],
'last_name' => $_POST['last_name'],
'email' => $_POST['email'],
];
$options = [
CURLOPT_URL => 'https://someEndpoint.com?encoding=UTF-8',
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_RETURNTRANSFER => 1
];
$curl = curl_init();
curl_setopt_array($curl, $options);
$results = curl_exec($curl);
curl_close($curl);
$response['success'] = true;
$response['message'] = 'Thank you, your request has been submitted.';
echo json_encode($response);
You're currently passing the post fields as an array.您当前正在将帖子字段作为数组传递。 However, cURL expects it to be passed as a string in this format:但是,cURL 期望它以这种格式作为字符串传递:
first_name=foo&last_name=bar&...
It's just like a query string.它就像一个查询字符串。
We can use http_build_query() to convert the array to the above format:我们可以使用http_build_query()将数组转换为上述格式:
CURLOPT_POSTFIELDS => http_build_query($data),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.