类似:Uncaught TypeError: Cannot use ‘in’ operator to search for ‘’ in JSON string
前端js&php笔记
正文:
在html页面中通过$.get()方法请求php页面,回调函数反回了json数据,但通过data点里面的数据时获取不出来,代码去下:
js代码:
$("#button1").click(function(){
$.get("index.php",{username:$("#username").val(),password:$("#password").val(),tel:$("#tel").val()},function(data,textStatus){ //get方法请求数据
$("#response").html("用户名:"+data.name+"<br/>密码:"+data.pwd+"<br/>手机号码:"+data.tell);
alert(data); //能够显示数据
})
})
php代码:
<?php
if(!empty($_GET["username"]) && !empty($_GET['password']) && !empty($_GET['tel'])){
$username = $_GET["username"];
$password = $_GET['password'];
$tel = $_GET['tel'];
$dataArray = array("name"=>$username,"pwd"=>$password,"tell"=>$tel);
$jsonStr = json_encode($dataArray);
echo $jsonStr;
}
?>
运行后:
能够返回数据
不能够 取出 返回的数据
解决办法:
创建一个对象,把json数据转换为对象
ajaxData=$.parseJSON(data) //将json数据转换为js对象
注:
不能在程序里面运行,程序里面运行解释不了php页面,必须在appserv程序下的www文件夹下运行(运行时不能是ftp地址,而是如“http://localhost:82/unit07/index.html”这样的地址)