使用javascript对外部URL的Ajax请求

时间:2014-03-29 12:07:03

标签: javascript php ajax

我试图对外部url.Right做一个ajax请求现在我在php中做它

作为

$data = array(
        'TokenID' => $tokenid,
        'APIKey' => $api_key,
        'EcryptedData' => $encrypted_data,
        'TokenScheme' => 4
    );
    //convert to JSON
    $json = json_encode($data);
    //curl config
       $ch = curl_init("https://testingonetwo.com/rest/");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                    'Content-Type: application/json', //we are using json in this example, you could use xml as well
                                    'Content-Length: '.strlen($json),
                                    'Accept: application/json')       //we are using json in this example, you could use xml as well
                                    );
       curl_setopt($ch, CURLOPT_POST, 1);
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
       curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

       $outputjson = curl_exec($ch);      

我试图用javascript做同样的事情。我用jquery尝试了这个,但没有成功

我试过的jquery代码是

$data = array(
        'TokenID' => $tokenid,
        'APIKey' => $api_key,
        'EcryptedData' => $encrypted_data,
        'TokenScheme' => 4);
$json = json_encode($data);
$.ajax({
    type: "POST",
    url: 'https://testingonetwo.com/rest/',
    data: {data:$json},
    success: success,
    dataType: "json"
});
alert(result);
function success(result) { 
    alert('done');
}

我对客户端浏览器脚本都不熟悉。请帮我尝试上面的javascript,我更喜欢。向前寻求帮助。

1 个答案:

答案 0 :(得分:4)

如果服务器不支持cors,或者不使用JSONP响应,则需要使用中间人脚本来获取数据。

JS

$.ajax({
    type: "POST",
    url: 'https://YourOwnDomain.com/myPhpScript.php',
    success: success,
    dataType: "json"
});

PHP

...
$outputjson = curl_exec($ch);
echo $outputjson;
die;

如果他们使用jsonp响应你可以使用jQuery的jsonp功能来获取数据,看看其他域的文档如何调用他们的休息服务他们应该有关于做jsonp调用的详细信息,如果他们允许它。一般代码如下:

$data = {
        'TokenID':$tokenid,
        'APIKey':$api_key,
        'EcryptedData':$encrypted_data,
        'TokenScheme':4};

$.ajax({
    type: "POST",
    url: 'https://testingonetwo.com/rest/?callback=?',
    data: {data:$data},
    success: success,
    dataType: "jsonp"
});

但是,如果你看起来像API密钥和TokenID,如果它们应该是秘密的(即最终用户不应该看到它们),那么你不应该使用显示这些细节的javascript,即使用中间人剧本。