Json请求在JavaScript中有效,但不适用于PHP

时间:2018-10-08 12:39:53

标签: javascript php jquery json

我正在尝试使用PHP获取JSON对象。当我使用Jquery尝试运行时,效果很好,但是当我使用PHP进行尝试时,则返回超时消息。

jQuery代码:

$(document).ready(function(){
    $.post("https://xxxxx/mig_search", {Keywords: 'test'}, function(result){
        var myObj = JSON.parse(result);
        $("body").html(result);
    });
});

PHP代码:

$url = "https://xxxxx/mig_search";

$postdata = http_build_query(
    array(
        'Keywords' => 'teste',
    )
);

$options = array('http' =>
    array(
    'method' => 'POST',
    'header' => 'User-Agent: request',
    'content' => $postdata,
));

$ctx = stream_context_create($options);

$result = file_get_contents($url, false, $ctx);
if (!empty($result)) {
    echo $result;
} else {
    echo "Nao funcionou!";
}
die;

2 个答案:

答案 0 :(得分:1)

请尝试以下代码

$postdata = http_build_query(array ('Keywords' => 'teste'));

$options = array (
'http' => array (
    'method' => 'POST',
    'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
        . "Content-Length: " . strlen($postdata) . "\r\n",
    'content' => $postdata
    )
);

答案 1 :(得分:0)

尝试添加内容标题:

'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
            . "Content-Length: " . strlen($postdata) . "\r\n",