『壹』 php传过来的json数据js怎么调用
<?php
header("Content-type:text/html;charset=utf-8");
if($_POST){
$d = $_POST['data'];//这里获取的直接就是数组了,不需要用到json_decode
echo $d['doing'];
//print_r($d);
exit;
}
?>
JS部分代码:
<script type="text/javascript">
$(document).ready(function() {
$("#xx").click(function(){
var url = "test.php";
var str ="{'doing':'createvote','type':'type','num':'num','votetheme':'votetheme','creater':'loginname'}";//json格式字符串
var data = eval('('+str+')');//转换成数组对象,不加这步,那么PHP获取的是字符串。
$.post(url, {'data': data}, function(res) {
alert(res);
});
});
});
</script>
<input id="xx" type="button" value="点击">
『贰』 php如何获取json中数据
可以用$obj=>key 的方式直接读取 也可以先转换为数组 用遍历数组的方法读取内
<?php
$json='{"a":100,"b":200,"c":300,"d":400,"e":500}';
//首先将json字符串容转换成关联数组
$arr=json_decode($json,true);
//然后循环读取数据
foreach($arras$item){
echo$item;
echo"<br/>";
}
?>
运行结果:
100
200
300
400
500
『叁』 请求外部接口返回json数据,php json_encode解码出现问题,有些数据无法显示。
一般使用php发送请求,获取返回的数据,进行解析;
<?php
$url="接口地址";
//发送请求获取返回值回,file_get_contents只支持答get请求,post使用curl
$json = file_get_contents($url);
//把json数据转化成数组
$data = json_decode($json,true);
//打印看看
print_r($data);
?>
『肆』 php如何读取json中的数据
先使用json_decode()函数解析成数组,在用变量等于解析出来的数组
$test=json_decode("json数据");
输出 echo $test->key;