【问题标题】:PHP echo data - append to html elementPHP 回显数据 - 附加到 html 元素
【发布时间】:2014-11-05 07:43:26
【问题描述】:

我将一些 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'));

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

【问题讨论】:

  • 究竟是什么不起作用?
  • 我想看到在 svg 元素#mapa 中放置的回显元素,意思是在屏幕上看到它们,这现在不会发生。

标签: php jquery html ajax svg


【解决方案1】:

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

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

【讨论】:

  • 它似乎几乎可以工作,但它没有被附加,因为 console.log 返回带有很多反斜杠的字符串,例如:"
  • @oneday 看看fiddle 处理替换。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
        $.post("./getElements", dataType:"html", function( data ) {
        $('#mapa').html(data);
        // or
        $('#mapa').append(data); // (your case)
        });
    

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

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 2014-02-24
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2023-04-03
      • 2017-12-05
      • 2023-01-16
      • 1970-01-01
      相关资源
      最近更新 更多