javascript – 提取Json响应

前端之家收集整理的这篇文章主要介绍了javascript – 提取Json响应前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我试图从PHP文件发送的jquery提取Json响应.
这是.js代码

@H_301_6@ $.ajax({ url: 'index.PHP?page=register',//This is the current doc type: 'POST',datatype: 'json',data: {'userCheck': username},success: function(data){ // Check if username is available or not },error: function(){ alert('Much wrong,such sad'); } });

这是来自PHP文件的响应:

@H_301_6@ if($sth->fetchColumn()!=0){ //$response = array("taken"); $response = array("username"=>"taken"); echo json_encode($response); //echo '{"username':'taken"}'; }else{ //$response = array("available"); $response = array("username"=>"available"); echo json_encode($response); //echo '{"username":"available"}'; }

我已经尝试了两种文件中我能想到的所有组合,但似乎没有任何效果.它是对数据库用户名的简单检查.如果我通过控制台记录我从响应中获得的数据,我得到这个:

@H_301_6@ {"username":"available"}

所以信息在那里,但我如何访问它?我在互联网上尝试了几种语法,但到目前为止还没有运气.我似乎记得一个json响应只能包含有效的json,那么问题是html吗?由于我的应用程序的结构,我不认为我可以避免这种情况,因此希望可以使用我目前的结构访问json.

最佳答案
在你Ajax

编辑:

更改

@H_301_6@datatype:"json",

如果不遵守参数名称的情况,则t必须为T.

@H_301_6@dataType:"json",

现在请重试

@H_301_6@$.ajax ({ url: 'index.PHP?page=register',//This is the current doc type: 'POST',dataType: 'json',success: function(data) { // Check if username is available or not switch(data.username) { case "available": // do you want break; case "taken": // do you want break; } },error: function() { alert('Much wrong,such sad'); } });

PHP

简单地说,不要忘记退出;避免在你的json响应中包含html页面
这是在……“….之后的代码,它打破了你的json输出
并使其无法读取javascript(更糟糕,它只是打破你的JavaScript!)

@H_301_6@echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]); exit;

猜你在找的jQuery相关文章