PHP echo数据 - 附加到html元素

时间:2014-09-11 11:19:27

标签: php jquery html ajax svg

我将一些html元素(或实际的< rect > svg元素)作为字符串存储在数据库中。

我有一个回复数据的PHP:

$db = getConnection();
$statement = $db->prepare('SELECT `copy` FROM `draggable`');
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$numberOfElements = count($result);
for ($i = 0; $i < $numberOfElements; $i++) {
    echo $result[$i]['copy'];
}
$statement->closeCursor();

浏览器响应中的回显结果是:

<rect class="draggable" x="385.53125" y="139" width="50" height="50" style="fill: rgb(0, 128, 0); fill-opacity: 0.2; position: relative; left: -445.46875px; top: 13px;" id="TmOZB"></rect>
<rect class="draggable" x="140.53125" y="276" width="50" height="50" style="fill: rgb(0, 0, 255); fill-opacity: 0.2; position: relative; left: -710.46875px; top: 148px;" id="wQXtQ"></rect>
<rect class="draggable" x="293.53125" y="99" width="50" height="50" style="fill: rgb(255, 0, 0); fill-opacity: 0.2; position: relative; left: -548.46875px; top: -28px;" id="atlxR"></rect>
<rect class="draggable" x="73.53125" y="136" width="50" height="50" style="fill: rgb(0, 128, 0); fill-opacity: 0.2; position: relative; left: -762.46875px; top: 18px;" id="fLuJl"></rect>

现在我希望通过Ajax获得该结果并将其附加到svg元素(id #mapa )。这就是我到目前为止所做的:

$('#mapa').append($.post('./getElements'));

但它不起作用。我应该改变什么?

3 个答案:

答案 0 :(得分:2)

$.post()会返回jqXHR,而非请求的结果。请求也是异步执行的。因此,您可以将请求的结果添加到$.post成功回调中的元素:

$.post('./getElements', function(data) { $('#mapa').append(data); }));

答案 1 :(得分:1)

假设你的php文件是getElements试试这个

$.post( "./getElements", function( data ) {
   $('#mapa').append(data);
});

答案 2 :(得分:0)

    $.post("./getElements", dataType:"html", function( data ) {
    $('#mapa').html(data);
    // or
    $('#mapa').append(data); // (your case)
    });

检查请求网址(./getElements),如果返回HTML数据是正确的。