使用ajax而不是使用带有curl的php文件从另一个网页获取响应

Using ajax instead of using a php file with curl to get a response from another webpage

本文关键字:文件 php 另一个 响应 获取 网页 curl ajax 使用      更新时间:2023-09-26

我有一项任务要找到一种停止使用php curl的方法,而且我必须只使用javascript而不使用jQuery。这是我的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;                
}

如果我遗漏了什么,请告诉我,我会补充更多细节。

这听起来像是javascript同源策略的结果。

您需要使用CORS或JSONp之类的技术来解决这个问题。上面的链接提供了更多详细信息。