我的任务是找到一种停止使用 php curl 的方法,并且我必须只使用没有 jQuery 的 javascript。这是我的 php 文件,它被另一个 ajax 调用:
$jsonData = json_decode(file_get_contents('php://input'));
$url ='https://api.#######.com/####'; // this is not my website, just using their api
$ch = curl_init();
$data = array(
'text' => $jsonData,
'from' => 'eng',
'to' => 'fra'
);
$data_encoded = json_encode($data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: SECRET apikey=###'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_encoded);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
echo $result;
这是我的新 ajax,但我收到此错误:NS_ERROR_FAILURE:失败
function getTranslation(a_data,from,to)
{
var json_array = {};
var url = 'https://api.#####.com/#####';
var xmlhttp;
json_array = { 'text': a_data,
'from' : 'eng',
'to' : 'fra' };
var json_data = JSON.stringify(json_array);
console.log(json_data);
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.setRequestHeader("Authorization","SECRET apiKey=###");
xmlhttp.send();
json_parsed = JSON.parse(xmlhttp.responseText);
return json_parsed.translation;
}
如果我错过了什么,请告诉我,我会添加更多细节。