如何从ajax调用的php响应中生成数组的jquery对象

时间:2015-08-31 06:07:26

标签: javascript php jquery

这是我的javascript变量my,我想从php文件中获取它。

selectAnnotation.php里面,我只是回应它

echo "{
    src : 'http://192.168.1.58/annotate/drive/image/test.jpg',
    text : 'Suresh and Gopinath....',
    shapes : [{
        type : 'rect',
        geometry : { x : 0.1825726141078838, y: 0.23756906077348067, width : 0.11602209944751381, height: 0.11618257261410789 }
    }]
}";
exit;

因为,我想从php文件中获取它。为了实现它,我做了一个ajax调用

    var my = {
    src : 'http://192.168.1.58/annotate/drive/image/<?php echo $_GET['file']?>',
    text : 'Suresh and Gopinath....',
    shapes : [{
        type : 'rect',
        geometry : { x : 0.1825726141078838, y: 0.23756906077348067, width : 0.11602209944751381, height: 0.11618257261410789 }
    }]
}
console.log(my);
console.log('__________');
    $.post("masterCall/selectAnnotation.php",
        { url: 'http://192.168.1.58/annotate/drive/image/<?php echo $_GET['file']?>'
        },
        function(data,status){
        console.log(data);
        console.log('__________');
        //anno.addAnnotation(data);
        });

在这样做时,我可以在控制台中看到差异..

以下是我执行console.log(my)console.log(data)

的控制台记录时会发生什么情况的屏幕

enter image description here

那么,我怎样才能做出正确的回应,就像在console.log(my)

中一样

注意:

var my是我需要的正确格式,我想从php文件中获取相同的格式并在jquery中获取它。

更新:

当我尝试

$v = "{
    src : 'http://192.168.1.58/annotate/drive/image/test.jpg',
    text : 'Suresh and Gopinath....',
    shapes : [{
        type : 'rect',
        geometry : { x : 0.1825726141078838, y: 0.23756906077348067, width : 0.11602209944751381, height: 0.11618257261410789 }
    }]
}";
echo json_encode($v);

和jquery

function(data,status){
        var obj = jQuery.parseJSON( data);
        console.log(obj);
        });

我和前一个人差不多......

3 个答案:

答案 0 :(得分:1)

尝试使用json_encode和json_decode来传输数据。 在js JSON.parse

答案 1 :(得分:1)

尝试像这样构建:

$Result = $Connection->query($Query); 
$result=array(); 
$i=0; 
while($row = $Result->fetch_assoc()){ 
$result[$i]['src']=$row['src']; 
$result[$i]['text']=$row['text']; 

$result[$i]['shapes'][]=array('type'=>'rect','geometry'=>array('x' => $row['x'], 'y'=> $row['y'], 'width' => $row['width'], 'height'=>$row['height']) ); 
$i++; 
} 
echo json_encode($result);

//成功后的javascript响应...

data=JSON.parse(data); 
for(var i=0;i<data.length;i++){ 
console.log(data[i]); 
}

答案 2 :(得分:0)

这是我在SO上的第一个答案。

我想正确的方法是使用eval()。但是建议使用jin_encode和json_decode,就像Ninjava建议的那样。