javascript - JQuery 在 ajax 加载数据库后不起作用

标签 javascript php jquery ajax

伙计们。

我正在尝试开发一个具有可拖动功能的网页。 我找到了我想要的 jQuery 主题,并且正在使用该代码。

我没有做太多修改,只是添加了使用 ajax 和 mysql 加载数据库的代码。 加载数据库后,可拖动功能不起作用。 我认为这是关于运行函数的顺序。 所以我在具有可拖动功能的函数上使用了 setTimeout,它起作用了。

但问题是我必须每 5 秒加载一次数据库,所以我不能在每次加载数据库时都对可拖动函数使用 setTimeout。

有什么解决方案可以解决这个问题吗?

这是我使用的代码

main.php

$(document).ready(function database(){

  if(window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp = new XMLHttpRequest();
  } else{
    // code for IE6, IE5
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange = function(){
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
      document.getElementById("gallery").innerHTML = xmlhttp.responseText;
    }
  };
  xmlhttp.open("GET","db.php",true);
  xmlhttp.send();

   init();
});
setTimeout(function (){

  var $gallery = $("#gallery");
  var $gallery2 = $("#gallery2");
  var $trash = $("#trash");
  var $trash2 = $("#trash2");
  $("li",$gallery).draggable({
    cancel: "a.ui-icon",revert:"invalid",containment:"document",helper:"clone",cursor:"move"
  });
  $("li",$gallery2).draggable({
    cancel: "a.ui-icon",revert:"invalid",containment:"document",helper:"clone",cursor:"move"
  });
  $trash.droppable({
    accept: "#gallery > li",
    classes: {
      "ui-droppable-active": "ui-state-highlight"
    },
    drop: function( event, ui ) {
      deleteImage( ui.draggable );
    }
  });
  $trash2.droppable({
    accept: "#gallery2 > li",
    classes: {
      "ui-droppable-active": "ui-state-highlight"
    },
    drop: function(event, ui){
      deleteImage2(ui.draggable);
    }
  });
  $gallery.droppable({
    accept: "#trash li",
    classes: {
      "ui-droppable-active":"custom-state-active"
    },
    drop: function(event, ui){
      recycleImage(ui.draggable);
    }
  });
  $gallery2.droppable({
    accept: "#trash2 li",
    classes: {
      "ui-droppable-active":"custom-state-active"
    },
    drop: function(event, ui){
      recycleImage2(ui.draggable);
    }
  });
  var recycle_icon = "<a href='link/to/recycle/script/when/we/have/js/off' title='Recycle this image' class='ui-icon ui-icon-refresh'>Recycle image</a>";
  function deleteImage( $item ) {
    $item.fadeOut(function() {
      var $list = $( "ul", $trash ).length ?
      $( "ul", $trash ) :
      $( "<ul class='gallery ui-helper-reset'/>" ).appendTo( $trash );
      $item.find( "a.ui-icon-trash" ).remove();
      $item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
        $item
        .animate({ width: "100px" })
        .find( "img" )
        .animate({ height: "150px" });
      });
    });
  }
  function deleteImage2( $item ) {
    $item.fadeOut(function() {
      var $list = $( "ul", $trash2 ).length ?
      $( "ul", $trash2 ) :
      $( "<ul class='gallery ui-helper-reset'/>" ).appendTo( $trash2 );
      $item.find( "a.ui-icon-trash" ).remove();
      $item.append( recycle_icon ).appendTo( $list ).fadeIn(function() {
        $item
        .animate({ width: "100px" })
        .find( "img" )
        .animate({ height: "150px" });
      });
    });
  }
  var trash_icon = "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a>";
  function recycleImage( $item ) {
    $item.fadeOut(function() {
      $item
      .find( "a.ui-icon-refresh" )
      .remove()
      .end()
      .css( "width", "96px")
      .append( trash_icon )
      .find( "img" )
      .css( "height", "72px" )
      .end()
      .appendTo( $gallery )
      .fadeIn();
    });
  }
  function recycleImage2( $item ) {
    $item.fadeOut(function() {
      $item
      .find( "a.ui-icon-refresh" )
      .remove()
      .end()
      .css( "width", "96px")
      .append( trash_icon )
      .find( "img" )
      .css( "height", "72px" )
      .end()
      .appendTo( $gallery2 )
      .fadeIn();
    });
  }
  function viewLargerImage( $link ) {
    var src = $link.attr( "href" ),
    title = $link.siblings( "img" ).attr( "alt" ),
    $modal = $( "img[src$='" + src + "']" );
    if ( $modal.length ) {
      $modal.dialog( "open" );
    } else {
      var img = $( "<img alt='" + title + "' width='384' height='288' style='display: none; padding: 8px;' />" )
      .attr( "src", src ).appendTo( "body" );
      setTimeout(function() {
        img.dialog({
          title: title,
          width: 400,
          modal: true
        });
      }, 1 );
    }
  }
  $( "ul.gallery > li" ).on( "click", function( event ) {
    var $item = $( this );
    var $target = $( event.target );
    if ( $target.is( "a.ui-icon-trash" ) ) {
      deleteImage( $item );
    } else if ( $target.is( "a.ui-icon-zoomin" ) ) {
      viewLargerImage( $target );
    } else if ( $target.is( "a.ui-icon-refresh" ) ) {
      recycleImage( $item );
    }
    return false;
  });
  $( "ul.gallery2 > li" ).on( "click", function( event ) {
    var $item = $( this );
    var $target = $( event.target );
    if ( $target.is( "a.ui-icon-trash" ) ) {
      deleteImage2( $item );
    } else if ( $target.is( "a.ui-icon-zoomin" ) ) {
      viewLargerImage( $target );
    } else if ( $target.is( "a.ui-icon-refresh" ) ) {
      recycleImage2( $item );
    }
    return false;
  });
}, 1000);

db.php

    <?php
$host = "localhost";    // 자신의 mysql
$DB_name = "master";    // 데이터베이스 이름
$user = "root";         // 기본 사용자.
$password = "0000";     // apm 기본 암호

$conn = mysqli_connect($host, $user, $password, $DB_name);

if(!$conn){
    echo "fail!\n";
    die('Could not connect: ' . mysqli_error($con));
}

//else
$sql = "select * from sensorlist";
$result = mysqli_query($conn,$sql);
$rowcnt = mysqli_num_rows($result);
$filed_name = array('S_Ultrasonic','S_IR','S_Humidity','S_Temperature','S_Heatindex','S_Light','S_Gas');    //센서 필드명 집합

if($rowcnt == 1){   //right (data가 1행만 들어있는 게 맞는 지 체크)
    while($row = mysqli_fetch_array($result)){
        for($i=0;$i<count($filed_name);$i++){
            if($row[$filed_name[$i]] != NULL){
                echo "<li class='ui-widget-content ui-corner-tr ui-draggable ui-draggable-handle'>";
                echo "<h5 class='ui-widget-header'>" . $filed_name[$i] . "</h5>";
                echo "<a href='images/high_tatras.jpg' title='View larger image' class='ui-icon ui-icon-zoomin'> View larger</a>";
                echo "<a href='link/to/trash/script/when/we/have/js/off' title='Delete this image' class='ui-icon ui-icon-trash'>Delete image</a></li>";
            }
        }
    }
    //echo "No sensor";
} else if($rowcnt == 0) {   //data가 하나도 없으면 없다고 출력
    //없다고 출력
    echo "No sensor";
} else {    //이도 저도 아니면 땡!
    //db 에러 출력
    echo "No sensor";
}
mysqli_close($conn);

?>

最佳答案

如果您动态添加了元素,则委托(delegate)您的事件,在 ajax 完成后重新初始化您的可拖动插件(在 onreadystatechange 事件的 if 中执行所有逻辑)

关于javascript - JQuery 在 ajax 加载数据库后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39361318/

相关文章:

php - 无法将 json 从客户端发送到 php 并接收来自 php 的 json 响应

javascript - 在 HTML 页面上居中对齐 JavaScript 脚本

php - Moodle安装脚本不起作用

php - mysql查询只选择第一条记录

javascript - 如何在angularjs中从数据库mysql加载动态记录?

javascript - 带有CSS转换的 slider 中的无限循环

Jquery animate 容器水平通过相对定位的页面

javascript - d3js 不要先输入动画

javascript - JavaScript 中文本区域输入长度检查

提交后,带有下拉列表的 php javascript 表单在我的 _GET 中有 %24