我有一个函数,使用mysql从php返回数组对象,我想使用javascript从ajax函数调用数组,但我不知道如何在javascript动态表或控制台日志中显示数组对象php。
我的php文件:
$age = $_POST["param"]; //value ajax param
$list = BussinesLayer::getUsers($age); //load my list
//list properties ej: list->getName(), getAge(), getOcupation()->getDescription(), etc..
echo json_encode($list); 我的js函数:
fnListUsers: function() {
var agedata = $("#txtAge").val();
$.ajax({
type : "POST",
url : "../ControllerFile/SearchUsers.php",
data : {"param" : agedata},
dataType : 'json',
success : global.fnSuccessList,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
}
});
},
fnSuccessList: function(data) {
var array = JSON.parse(data); // -> dont work Uncaught SyntaxError: Unexpected token o in JSON at position 1
var array2 = jQuery.parseJSON(data); // dont work Uncaught SyntaxError: Unexpected token < in JSON at position 0
//how display my arrayobject ?
console.log(data.getName, data.getOcupation.getDescripition);
}发布于 2017-06-11 15:39:11
您的成功函数已经有了json格式的data。因此您不需要在JSON中再次解析它。只需使用console.log(data)查看您的对象即可。
fnSuccessList: function(data) {
var array = JSON.parse(data); // remove this
var array2 = jQuery.parseJSON(data); // remove this
console.log(data);
}发布于 2017-06-11 15:48:21
这里您做错了,您使用了已经解析数据的dataType : 'json',但在此之后,您再次尝试解析。这会导致错误。
fnListUsers: function() {
var agedata = $("#txtAge").val();
$.ajax({
type : "POST",
url : "../ControllerFile/SearchUsers.php",
data : {"param" : agedata},
dataType : 'JSON',
success : global.fnSuccessList,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
}
});
},
fnSuccessList: function(data) {
// this will show your data
console.log(data);
/* Don't use this just access data directly
var array = JSON.parse(data); // -> dont work Uncaught SyntaxError: Unexpected token o in JSON at position 1
var array2 = jQuery.parseJSON(data); // dont work Uncaught SyntaxError: Unexpected token < in JSON at position 0
*/
}在控制台中查看,如果您的数据如下所示,则它已被解析

如果看起来像这样,那么它就不会被解析

https://stackoverflow.com/questions/44481030
复制相似问题