dragam0217 2017-05-23 04:34
浏览 38
已采纳

即使变量可用,ajax调用也不成功

In this code i m trying to populate dropdown list, when the variable $place is available. Made an ajax call to get the data from the listplace.php file which is encoded in json format

Problem is the dropdown list not populating from the php file done through ajax call. But when i echo $_GET['place']; it works and also the listplace.php also contains data but still not the dropdown populating. Please help!!

listplace.php output

{"option":["HBD T-Shirt"]}

Php Code

<?php
echo $_GET['place'];
?>

<select id="name">
  <option selected disabled>Please select</option>
</select>


<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
    <script>
        $.ajax({
            type: "POST",
            data: {place: '<?= $_GET['place'] ?>'},
            url: 'listplace.php',
            dataType: 'json',
            success: function (json) {
                if (json.option.length) {
                    var $el = $("#name"); 
                    $el.empty(); // remove old options
                    for (var i = 0; i < json.option.length; i++) {
                        $el.append($('<option>',
                            {
                                value: json.option[i],
                                text: json.option[i]
                            }));
                    }
                }else {
                    alert('No data found!');
                }
            }
        });
    </script>
<?php } ?>
  • 写回答

1条回答 默认 最新

  • dongshao2967 2017-05-23 06:55
    关注

    finally found out the solution due to a simple mistake, that instead of $place i mentioned as $variable now the ajax works perfectly.

    There is a code window.location = "1stlink.php?place=" + encodeURIComponent(textval); here instead of $place i had put $variable so it dint work.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?