javascript - 通过 php 使用 jQuery $.ajax 从 MySQL 检索数据 - 异步问题

标签 javascript php jquery mysql ajax

我在异步处理 jquery ajax 调用 PHP 所请求的数据时遇到了麻烦。我正在从 MySQL 读取数据。

数据读取正确,但在 PHP 提供数据之前 JavaScript 就开始进行处理。控制台日志显示这一点是因为尽管 $ajax success: 之后存在数据,但我想要的位置缺少数据,而且日志条目的顺序是相反的。

我在 SO 和其他地方看到了几个类似的问题,例如: jquery to php (wait for php script until result/finish) Wait for external method to complete before finishing? 但这些对我没有帮助。抱歉没看懂。

我尝试了ajaxComplete方法,但没有解决问题。我尝试将值(list_items 和 status)加载到 div 中,我可以在 HTML 页面中看到它,但尝试从那里检索它返回“”,因此当我尝试获取其文本时它显然还不存在。

我相信答案涉及回调的使用,但我还没有找到一个可以适应我的代码的示例,因为我无法理解如何在下面的情况下使用回调,尽管阅读了 http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/ 和其他来源。

console.log shows this:
list_items:    status:                       5.html:29
list_items: 3List Items   status: OK         5.html:12

这是我的 5.html

<html>
  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <script>
/* function to READ from MySQL */
    function readMySQL( user_id, todo_name ){
        var params = {user_idPOST: user_id, todo_namePOST: todo_name, action: "read"};
        $.ajax({ type: "post", url: "5.php", data: params, datatype: "text",
            success: function(data){
                list_items = data;
                status = 'OK';
                console.log('list_items:', list_items, '  status:', status); // this is 5.html:12
            },
            error: function(jqXHR, exception) { errorMySQL(jqXHR, exception); }
        });
    }
/* function to signal ERRORS */
    // error handling
    }
/* Start */
    $(document).ready(function(){
        window.list_items = "";
        window.status = "";
        $("#read").click(function(){
            var user_id=3;
            var todo_name='3name';
            readMySQL( user_id, todo_name ); 
            console.log('list_items:', list_items, '  status:', status); // this is 5.html:29
        });
    });
    </script>
  </head>
    <body>
        <form>
            <input type="button" value="Read" id="read"><p>
        </form>
   </body>
</html>

这是 5.php

<?php
  $host = "localhost";  $user = "root";  $pass = "";    $databaseName = "informat_todo";
  $tableName = "todo_list";
  $con = mysqli_connect ( $host, $user, $pass, $databaseName );

  // Check connection
  if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
  $action = $_POST["action"];
  $user_id = $_POST["user_idPOST"]; 
  $todo_name = $_POST["todo_namePOST"];

// READ ------------------------------------------------------------------------------------------
    if($action=="read"){
        $show = mysqli_query ( $con, "SELECT * FROM $tableName WHERE user_id='$user_id' AND todo_name='$todo_name' " );
        $found = 0;
        while($row=mysqli_fetch_array($show)){
            $found = 1;
            echo $row[2] ;
        }
        if ($found==0) { echo "failed : "; echo $user_id; echo " / ";   echo $todo_name; echo " not found:"; } 
      }
    else {
        echo "failed : unknown action";
    }
?>

最佳答案

Javascript经常使用异步处理。这意味着,您启动一​​个事物,而不是等待它完成(没有办法“等待” - 这是故意的),而是向它传递一些代码以在处理完成时运行。

一开始这有点难以适应!您必须像这样更改“正常”数据流:

v = 计算一些数据(); doSomethingWithData(d)

像这样:

onFinish = 函数(d) { doSomethingWithData(d); } 计算一些数据(完成时)

无论你想要“等待数据”是什么(你并没有真正在这里向我们展示)......那个东西应该在你的 success() 回调中从 ajax 开始运行。

关于javascript - 通过 php 使用 jQuery $.ajax 从 MySQL 检索数据 - 异步问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25727495/

相关文章:

javascript - 编码 HTML 和 JavaScript

php - .htaccess 重写规则帮助

php - MySQL num_rows 返回误报

javascript - 如何在 jQuery DataTables 中按日期范围添加自定义搜索?

javascript - 如何在 javascript 中访问对象的内容?

javascript - 如何通过 jQuery $.ajax() 将 JSON 字符串发送到服务器?

javascript - 10 分钟不活动后显示弹出窗口

javascript - CKEditor 4.7 无法读取未定义的属性 'on',请用ajax咨询并重置

php - 防止 sed 扩展变量

javascript - 我想在 jQuery 上获取 $(this) 内元素的文本内容