为什么AJAX函数不能立即从数据库获取数据?

时间:2018-07-14 15:12:15

标签: javascript php html ajax

我有2个AJAX脚本:

1st使HTML表的第一个单元格可编辑,并将输入的值直接写入DB表;

2nd从DB表和HTML表的第二个单元格中提取数据。

顺序是这样

  1. 用户单击第一个HTML表格的单元格,然后对其进行编辑。 AJAX脚本将其写入数据库。

  2. PHP脚本将此数据添加到某个变量中,并在DB中写入答案。

  3. AJAX脚本立即从第二个HTML表的单元格中的数据库和鞋子中获取数据。

脚本是这样的: 1。 Edit.js:

   function showEdit(editableObj) {
     $(editableObj).css("background","#FFF");
   } 

  function saveToDatabase(editableObj,column,id) {
    $(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat right");
  $.ajax({
    url: "days.php",
    type: "POST",
    data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
    success: function(data){
     $(editableObj).css("background","#FDFDFD");

      //$(editableObj).css("background","#FDFDFD");
     // $("#birthday-data").replaceWith(data); //The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call
    }        
   });
}

2。 Show.js:

$(document).ready(function() {           

  $.ajax({    // create an ajax request
    type: "POST",
    url: "days.php",             
    dataType: "text",   // expect html to be returned                
    success: function(response){                    
        $("#one").html(response); // get the element having id of "one" and put the response inside it
        //alert(response);

  }        

}

3。 Table.php:     //这是带有HTML表的PHP脚本的内容部分

<td aria-label="First column" contenteditable="true" onBlur="saveToDatabase(this,'select1','<?php echo $show[$k]["id"]; ?>')" onClick="showEdit(this);"><?php echo $show[$k]["select1"]; ?></td>
      <td id="one"><?php echo $value['day1']; ?></td>

问题是我必须刷新页面才能看到我的HTML-table 2单元更新。期望在第一个单元格的数据编辑后立即更新。 认为问题出在show.php中,无法获取。需要帮助!

2 个答案:

答案 0 :(得分:1)

function saveToDatabase(editableObj,column,id) {
    $(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat right");
  $.ajax({
    url: "days.php",
    type: "POST",
    data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
    success: function(data){
     $(editableObj).css("background","#FDFDFD");

      //$(editableObj).css("background","#FDFDFD");
     // $("#birthday-data").replaceWith(data); //The .replaceWith() method removes content from the DOM and inserts new content in its place with a single call

    $("#one").text(data);
    }        
   });
}

我相信您只是想从days.php中获取响应以显示在表格单元格中...嗯,这就是您的方法。 'data'是days.php的预期收益,因此days.php将在'column ='+ column +'&editval ='+ editableObj.innerHTML +'&id ='+ id为发送到该页面...然后将其直接放到单元格中。

答案 1 :(得分:0)

我想我已经弄清楚了。

问题是,页面完全加载后,您要求查看更新。那就是您的脚本'Show.js' $(document).ready(function() {

但是您想在saveToDatabase函数完成后立即调用它。

因此,您必须更改 Show.js 函数并创建类似这样的函数

function showDoneEdits(obj){
}

然后在saveToDatabase函数的末尾可以调用showDoneEdits函数。更新过程完成后,这将立即开始显示过程。

请让其他人知道它是否有效。 :)