如何用来自Ajax的响应数据填充div?

时间:2020-07-30 12:51:16

标签: javascript html jquery ajax

我有一个Ajax发布请求,成功后返回一个我想加载到div中的数组。现在,使用单个值执行此操作非常容易,但是使用数组时,我似乎找不到正确的方法。

<fieldset id="div1" ondrop="remove_from_customer(event)" ondragover="allowDrop(event)">
<legend>Vacant parking spots</legend>
<?php $counter = 0;
echo count(get_free_parking_spots());
foreach (get_free_parking_spots() as $row) { ?>
    <div id="count_id<?php echo $counter; ?>" data-parking_gate="<?php echo $row['parking_gate_id']; ?>" data-location_id="<?php echo $row['location_id']; ?>" data-spot_no="<?php echo $row['spot_no']; ?>" draggable="true" ondragstart="drag(event)">
        <label><?php echo '' . $row['name'] . '' ?></label>
        <label><?php echo '<p>Gate: ' . $row['parking_gate_id'] . '<p>Spot: ' . $row['spot_no'] . '' ?></label>
    </div>
<?php $counter++;
} ?>
 </fieldset>
 <fieldset id="div2" ondrop="drop_to_customer(event)" ondragover="allowDrop(event)">
    <legend>Current parking spots of the customer</legend>
    <?php $count = 0;
    echo count(get_customer_parking_spots($selected_user_id));
    foreach (get_customer_parking_spots($selected_user_id) as $user) { ?>
        <div id="count_idd<?php echo $count; ?>" data-customerid="<?php echo $user['customer_id']; ?>" data-gate_id="<?php echo $user['gate_id']; ?>" data-spot_id="<?php echo $user['spot_id']; ?>" data-location_id="<?php echo $user['location_id']; ?>" draggable="true" ondragstart="drag(event)">
            <label><?php echo '' . $user['location_name'] .  '' ?></label>
            <label><?php echo '<p>Gate: ' . $user['gate_id'] . '<p>Spot: ' .  $user['spot_id'] ?></label>
        </div>
    <?php $count++;
    } ?>
</fieldset>

Ajax:

    function drop_to_customer(ev) {           
        if (<?php echo count(get_customer_parking_spots($selected_user_id)); ?> < 3) {
            const el = document.querySelector("[id=" + "\'" + ev.dataTransfer.getData("text") + "\'" + "]");
            
            var add_location = "add location";
            ev.preventDefault();
            var data = ev.dataTransfer.getData("text");
            ev.target.appendChild(document.getElementById(data));

            $.ajax({
                type: 'post',
                url: 'external_submit.php',
                data: {
                    add_spot: add_location
                },
                success: function(html) {
                    $('#div1').html($('#div1', html).html()); //my failed attempt to reload data into the div here
                }
            });
        }
    }

如您所见,当调用drop_to_customer()时,我正在执行一个发布请求,并返回一个数组,我想将该数组加载到ID为div1的另一个div中。该数组经过json_Encoded编码,并成功返回。

编辑: 这就是我在PHP中回显数组的方式:

echo json_encode(array("array" => get_data($_POST['id']), "html" => $html))

0 个答案:

没有答案