AJAX php请求外部URL

时间:2014-05-10 12:42:45

标签: php jquery ajax

我一直在尝试向外部网址发送ajax post请求,当我在网站hurl.it中尝试相同的请求时,它会给出正确的响应但是当我尝试使用浏览器时,我不会# 39;获取浏览器。

在hurl.it中,我输入了https url,标题中的content-length和请求正文是一个json字段。但是当我使用以下代码发送相同的参数时,我得到200 OK没有响应或400拒绝没有任何响应。

    var parameter = some json data;
    $.ajax({
                    url:"external-url",
                    type: 'POST',
                    data : parameters,
                    headers:{
                        "Content-Length" : 10070
                    },
                    success: function(data){
                        alert('success');
                    }
            });

后来我尝试使用PHP的POST请求,但也没有得到任何响应。

$url = "external-url"
$data = json_encode($data1);
// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
        'Content-Length' => 10070
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);

var_dump($result);

php代码给了我一个结果bool(false)。我不知道结果意味着什么,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:0)

如果外部网址是某个其他网域,则默认情况下无法调用其他域名,则允许在同一域名内进行Ajax调用。

如果是跨域服务调用,那么您可能需要jsonp服务。

这是一个例子:

$.ajax({
            crossDomain: true,
            url: "yourexternalURL?callback=?",
            data: parameters, // pass the data
            dataType: "jsonp",                
           //this is very important since it's the callback we will and that allow cross domain
            jsonp: 'jsonp_callback',
            success : function(data){
                 // process the data
            }
        });

在服务器中:

    <?php

$data = '{}'; // json string

if(array_key_exists('callback', $_GET)){

    header('Content-Type: text/javascript; charset=utf8');
    header('Access-Control-Allow-Origin: http://www.example.com/');
    header('Access-Control-Max-Age: 3628800');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

    $callback = $_GET['callback'];
    echo $callback.'('.$data.');';

}else{
    // normal JSON string
    header('Content-Type: application/json; charset=utf8');

    echo $data;
}
?>