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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改