0

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;                
}

何か見逃した場合はお知らせください。詳細を追加します。

4

1 に答える 1