我有一个函数,使用mysql从php返回数组对象,我想使用javascript从ajax函数调用数组,但我不知道如何在javascript dinamic表或控制台日志中显示数组对象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);
}
答案 0 :(得分:1)
您的成功函数已经具有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);
}
答案 1 :(得分:0)
这里你做错了你使用已经解析过数据的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
*/
}