2012-10-04 56 views
-1

我正在尝试通过http调用php脚本并从我打算进一步处理的地方接收json对象。使用JSON响应从PHP文件发出http请求

基本上,代码如下:

<?php 
    if ($_SERVER['REQUEST_METHOD'] === 'GET') { 
     $version=$_GET["v"]; 
     $product=$_GET["p"]; 
     $stream=$_GET["s"]; 
     $cmd=$_GET["c"]; 

     $string = file_get_contents("http://localhost:82/releasenote/src/getTSBDetails.php?p=$product&v=$version&s=$stream&c=$cmd"); 
     print_r($string); 
     exit(); 
    } else { 
     print("2"); 
     $string = file_get_contents('tsbDetails.json'); 
    } 

当get_file_contents HTTP请求是在浏览器中直接调用时,输出是一个JSON,但使用试图当上述没有响应。

+0

是您的机器==本地主机? – user1365836

+0

你能缩小范围吗?哪些案件不起作用?你如何“使用”它(在ajax调用中,直接在浏览器中)? –

+0

_“没有回应”_ - 这是不可能的。你是什​​么意思_“但是当试图使用上述”_?如果你发布它?它应该输出一个'2'。你不会在else中回显$ string。 – CodeCaster

回答

2

enter image description here

<?php 
     // JSon request format is : 
     // {"userName":"[email protected]","password":"12345","emailProvider":"zzzz"} 

     // read JSon input 
     $data_back = json_decode(file_get_contents('php://input')); 

     // set json string to php variables 
     $userName = $data_back->{"userName"}; 
     $password = $data_back->{"password"}; 
     $emailProvider = $data_back->{"emailProvider"}; 

     // create json response 
     $responses = array(); 
     for ($i = 0; $i < 10; $i++) { 
      $responses[] = array("name" => $i, "email" => $userName . " " . $password . " " . $emailProvider); 
     } 

     // JSon response format is : 
     // [{"name":"eeee","email":"[email protected]"}, 
     // {"name":"aaaa","email":"[email protected]"},{"name":"cccc","email":"[email protected]"}] 

     // set header as json![enter image description here][2] 
     header("Content-type: application/json"); 

     // send response 
     echo json_encode($responses); 
     ?> 


    [1]: http://i.stack.imgur.com/I7imt.jpg 
    [2]: http://i.stack.imgur.com/XgvOT.jpg 
+0

这是他的有用信息,所以我只是把它! – Rush

0

你应该确保你的变量可以在URL中使用的第一:

$version=urlencode($_GET["v"]); 
    $product=urlencode($_GET["p"]); 
    $stream=urlencode($_GET["s"]); 
    $cmd=urlencode($_GET["c"]); 

那么你应该检查你是否在$string读出的值是有效的JSON。你可以使用this answer

然后,如果你的字符串包含有效的json,你应该只是echo它。

最后,如果你总是希望从你的脚本JSON,你也应该json_encode错误处理:

} else { 
    echo json_encode("2"); 
    // $string = file_get_contents('tsbDetails.json'); /* commented out as you don't seem to use it */ 
}