下拉列表中的AJAX功能实时预览 [英] AJAX Function live preview from drop down list

查看:83
本文介绍了下拉列表中的AJAX功能实时预览的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在通过AJAX配置数据实时预览时遇到了一些麻烦.我设法通过以下代码进行预览,但是我对如何进行操作有些困惑.我的下一步是显示从同一表提供的图像URL.因为我是PHP和AJAX的新手(尤其是我),所以我对这段代码没有更多的了解. HTML的外观如下:

I'm having a little trouble configuring a live preview of data via AJAX. I managed to get a preview with the following code but I'm a bit stuck in how to proceed. My next step is displaying the image url provided from the same table. As I am fairly new to PHP and AJAX (especially) I'm not getting any further with this code. This is how the HTML looks like:

PHP逻辑:

$query = $conn->prepare("SELECT * FROM items WHERE user_id = $userID");
$query->execute();

HTML表单:

<div class="form-group">
<div id="results"></div>

<form action="" method="post">
  <label for="sel1">Selecteer uw items:</label>

  <select class="form-control" id="sel1"multiple>

    <?php
        while ($q = $query->fetch()){
          echo '<option value="' . $q['id'] . '">' . $q['Beschrijving'] 
          . '</option>';
        }
    ?>

  </select>

  <button type="button" class="btn btn-success" name="submit">Toevoegen 
   aan board</button>
 </form>

 </div>

Ajax/JS脚本:

The Ajax/JS script:

<script type="text/javascript">
$("#sel1").on("change", function(){
function clearpost(){
  $("#results").val("");
}

var selected = $(this).val();
makeAjaxRequest(selected);
function makeAjaxRequest(opts){
  $.ajax({
    type:"POST",
    data:{opts: opts},
    url:"views/itemOverview.php",
    success:function(res){
      $("#results").html("<p>Uw items : " + res + "</p>");
    }
  })
}

})
</script>

PHP文件:

echo '<pre>';
print_r($_POST);
echo '</pre>';

这是结果:

非常感谢所有反馈! 亲切的问候

All feedback is much appreciated! Kind regards

推荐答案

在您的情况下,PHP文件应返回可在ajax成功回调中使用的json对象.请从服务器中返回JSON,以从PHP脚本中返回JSON .如果对象样本代码像这样,

In your case the PHP file should return json object that you can use in ajax success callback. Please refer Returning JSON from a PHP Script from returning json from server. in case of object sample code goes like,

$res = new stdClass();
$res->name = "sample"; // from db
$res->imageUrl = "img/img1.png";// from db
echo json_encode($res);

在您的js文件中,您可以执行类似的操作

In your js file you can do something like,

$.ajax({
    type:"POST",
    data:{opts: opts},
    url:"views/itemOverview.php",
    datatype: "text/json", // this is preferred when receiving json data
    success:function(res){
      // res is json object. res.name & res.imageUrl are it's property
      $("#results").html("<p>Uw items : " + res.name + " <img src='"+ res.imageUrl+"' /></p>");
    }
  })

这篇关于下拉列表中的AJAX功能实时预览的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆