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 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图