使用JSON响应从PHP文件发出http请求
我正在尝试通过http调用php脚本,并从计划进一步处理的位置接收json对象 基本上,守则如下:使用JSON响应从PHP文件发出http请求,php,json,http,Php,Json,Http,我正在尝试通过http调用php脚本,并从计划进一步处理的位置接收json对象 基本上,守则如下: <?php if ($_SERVER['REQUEST_METHOD'] === 'GET') { $version=$_GET["v"]; $product=$_GET["p"]; $stream=$_GET["s"]; $cmd=$_GET["c"]; $string = file_get_cont
<?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,但尝试使用上述命令时没有响应。
<?php
// JSon request format is :
// {"userName":"654321@zzzz.com","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":"eee@zzzzz.com"},
// {"name":"aaaa","email":"aaaaa@zzzzz.com"},{"name":"cccc","email":"bbb@zzzzz.com"}]
// 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
首先,您应该确保您的变量可以在url中使用:
$version=urlencode($_GET["v"]);
$product=urlencode($_GET["p"]);
$stream=urlencode($_GET["s"]);
$cmd=urlencode($_GET["c"]);
然后,您应该检查在$string中读取的值是否是有效的json。你可以用它
然后,如果您的字符串包含有效的json,您应该只回显它
最后,如果您总是希望脚本使用json,那么还应该对错误处理进行json_编码:
} else {
echo json_encode("2");
// $string = file_get_contents('tsbDetails.json'); /* commented out as you don't seem to use it */
}
你的机器==localhost吗?你能把范围缩小一点吗?哪些案例不起作用?如何在ajax调用中直接在浏览器中使用它?没有响应-这是不可能的。当你尝试使用上面的方法时,你所说的“但是”是什么意思?如果你把它寄出去?然后它应该输出一个“2”。在else中不回显$string。