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

Javascript 使用ajax而不是使用带有curl的php文件从另一个网页获取响应,javascript,curl,xmlhttprequest,Javascript,Curl,Xmlhttprequest,我的任务是找到一种停止使用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 = ar

我的任务是找到一种停止使用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\u error\u FAILURE: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;                
}

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

这听起来像是一个错误的结果


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

我从中尝试了一些东西,但不适用于我。你能给我举个例子吗?到目前为止你试过什么?这里有一个包含一些exmaples的站点:。还请注意,对于CORS,您必须在向其发出请求的服务器上启用它:我想创建一个google扩展,这就是我想停止使用php的原因,因此我认为我不会有服务器。我从以下示例中尝试过:访问控制允许来源:访问控制允许方法:POST、GET、选项访问控制允许标头:X-PINGOTHER Access Control Max Age:1728000这些设置需要应用于您向其发送请求的服务器。你有权访问那个服务器吗?如果没有,我不确定你能做到。在构建扩展时,可能有一种请求跨源权限的方法,安装扩展的用户必须同意,但我只是在猜测。这是一个完全独立的问题,应该作为一个新帖子提出。以下是关于使用chrome扩展的CORS许可的信息: