douruhu4282 2014-09-08 15:12
浏览 50
已采纳

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

I'm in trouble with async processing of data requested by a jquery ajax call to PHP. I'm reading data from MySQL.

The data is being read correctly, but javascript is plunging on with the processing before PHP has supplied the data. The console log shows this both because of the absence of the data where I want it despite it's presence after $ajax success:, and because the order of log entries is reversed.

I've seen several similar questions on SO and elsewhere, like: jquery to php (wait for php script until result/finish) Wait for external method to complete before finishing? but these didn't help me. Sorry for not understanding.

I tried ajaxComplete method but that didn't solve it. I tried loading the values (list_items and status) into a div, where I could see it in the HTML page, but trying to retrieve it from there returned '', so it was apparently not there yet when I tried to fetch its text.

I believe the answer involves the use of callbacks, but I haven't found an example that I can adapt to work in my code, as I can't understand how to use callbacks in the circumstances below, despite reading http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/ and other sources.

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

here's my 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>

and here's 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";
    }
?>
  • 写回答

2条回答 默认 最新

  • dongxueji2838 2014-09-08 15:26
    关注

    Javascript often uses asynchronous processing. That means, you start a thing, and instead of waiting for it to finish (there's no way to "wait" - that's intentional), you pass it some code to get run when the processing is done.

    This is sort of hard to get used to at first! You have to change "normal" data flows like this:

    v = calculateSomeData(); doSomethingWithData(d)

    to something like this:

    onFinish = function(d) { doSomethingWithData(d); } calculateSomeData(onFinish)

    Whatever thing thing you want to "wait for the data" is (you don't really show us here)... that thing should be set off running in your success() callback from the ajax.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 欧拉系统opt目录空间使用100%
  • ¥15 ul做导航栏格式不对怎么改?
  • ¥20 用户端如何上传图片到服务器和数据库里
  • ¥15 现在研究生在烦开题,看了一些文献,但不知道自己要做什么,求指导。
  • ¥30 vivado封装时总是显示缺少一个dcp文件
  • ¥100 pxe uefi启动 tinycore
  • ¥15 我pycharm运行jupyter时出现Jupyter server process exited with code 1,然后打开cmd显示如下
  • ¥15 可否使用carsim-simulink进行四轮独立转向汽车的联合仿真,实现四轮独立转向汽车原地旋转、斜向形式、横移等动作,如果可以的话在carsim中如何进行相应设置
  • ¥15 Caché 2016 在Java环境通过jdbc 执行sql报Parameter list mismatch错误,但是同样的sql使用连接工具可以查询出数据
  • ¥15 疾病的获得与年龄是否有关