This will return only one row how to simply pass that row to ajax call. below code passing data , but when i print it in loop it print unlimited times.
这将只返回一行如何简单地将该行传递给ajax调用。下面的代码传递数据,但当我在循环中打印它时,它打印无限次。
AJAX::
$.ajax({
type: "POST",
url: 'userLoginCheckforRetrieve.php',
data: {
},
success:function(data) {
alert('outside loop is '+data);
for(var i=0; i < data.length ; i++){
alert('loop date is '+data[i].name);
}
}
});
PHP ::
$sel_query= "SELECT image_name FROM save_designs WHERE user_name='{$username}'";
$sel_result = mysql_query($sel_query);
$data = array();
while($item = mysql_fetch_object($sel_result))
{
$data[] = array(
'name' => $item->image_name
);
}
echo json_encode($data);
2 个解决方案
#1
0
Use JSON.parse
to parse a string as JSON. Try this:
使用JSON.parse将字符串解析为JSON。试试这个:
$.ajax({
type: "POST",
url: 'userLoginCheckforRetrieve.php',
data: {}, //Pass data here
success:function(data) {
var obj = JSON.parse(data); // parse a string as JSON
alert('outside loop is '+data);
for(var i=0; i < obj.length ; i++){
alert('loop date is '+obj[i].name);
}
}
});
#2
0
You should add a JSON parser to convert it...
你应该添加一个JSON解析器来转换它...
$.ajax({
type: "POST",
url: 'userLoginCheckforRetrieve.php',
data: {},
success:function(data) {
data = $.parseJSON(data);
for(var i=0; i < data.length; i++){
alert('loop date is '+data[i].name);
}}
});
The json returned is a string so by parsing it you will create an object that contain all the json string elements and their values.
返回的json是一个字符串,因此通过解析它,您将创建一个包含所有json字符串元素及其值的对象。
Note: make sure you php files has no warnings that are printed and that the returned page is a clean JSON string => { .... }
注意:确保php文件没有打印的警告,并且返回的页面是干净的JSON字符串=> {....}
have Fun!
#1
0
Use JSON.parse
to parse a string as JSON. Try this:
使用JSON.parse将字符串解析为JSON。试试这个:
$.ajax({
type: "POST",
url: 'userLoginCheckforRetrieve.php',
data: {}, //Pass data here
success:function(data) {
var obj = JSON.parse(data); // parse a string as JSON
alert('outside loop is '+data);
for(var i=0; i < obj.length ; i++){
alert('loop date is '+obj[i].name);
}
}
});
#2
0
You should add a JSON parser to convert it...
你应该添加一个JSON解析器来转换它...
$.ajax({
type: "POST",
url: 'userLoginCheckforRetrieve.php',
data: {},
success:function(data) {
data = $.parseJSON(data);
for(var i=0; i < data.length; i++){
alert('loop date is '+data[i].name);
}}
});
The json returned is a string so by parsing it you will create an object that contain all the json string elements and their values.
返回的json是一个字符串,因此通过解析它,您将创建一个包含所有json字符串元素及其值的对象。
Note: make sure you php files has no warnings that are printed and that the returned page is a clean JSON string => { .... }
注意:确保php文件没有打印的警告,并且返回的页面是干净的JSON字符串=> {....}
have Fun!