Tag Archive synchronous

Byphunsanit

jQuery Ajax แบบอนุกรมตามลำดับ

งานที่ทำอยู่ต้องใช้เจคิวรี่เอแจ็คไปเรียกใช้สร้างตารางในฐานข้อมูลใหม่ แต่ถ้าใช้ ajax หลายๆ ชุดต่อๆ กันแทนที่มันจะทำงานตามลำดับแบบอนุกรม มันดันไปทำงานแบบขนานแทน บางตารางที่ต้องสร้างหลังเพราะกำหนดความสัมพันธ์ไว้กับตารางหลัก แต่ตารางหลักยังสร้างไม่เสร็จ ผลคือ การสร้างตารางทำไม่สำเร็จ

แก้ได้โดยบังคับให้ รอฟังก์ชั่นเดิมเสร็จก่อนแล้วจึงทำงานอื่นๆ ต่อไป

jQuery.Ajax.synchronous.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery Ajax Synchronous By Pitt Phunsanit</title>
</head>
<body>
<div id="logs"></div>
<script src="../jQuery/jquery-2.1.3.min.js"></script>
<script>
$(function(){
 
    logs = $('#logs');
 
    /* task order */
    var tasks = new Array();
    tasks.push('one');
    tasks.push('two');
    tasks.push('three');
 
 
 
    /* process each step */
    function step(tasks, a)
    {
        $.ajax({
            "cache" : false,
            "data" : 'task='+tasks[a],
            "dataTyp" : "html",
            "method" : "post",
            "success" : function(datas)
            {
 
                logs.append(datas);
 
                /* call next step */
                a++;
                if(typeof tasks[a] != 'undefined')
                {
                    step(tasks, a);
                }
 
            },
            "url" : 'task.php'
        });
    }
 
    /* call first time */
    step(tasks, 0);
});
</script>
</body>
</html>
task.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
switch($_POST['task'])
{
    case 'one' :
    {
        echo '<h1>One</h1>';
    }break;
    case 'two' :
    {
        echo '<h1>Two</h1>';
    }break;
    case 'three' :
    {
        echo '<h1>three</h1>';
    }break;
}

ทีนี้มันจะทำงานตามลำดับ 1,2,3… อย่างถูกต้อง

ถ้าต้องการหยุดการทำงาน เช่น มี error ให้เปลี่ยนค่า a เป็นค่าที่ไม่มีอยู่จริง เช่น 9999 (คงไม่มี process กลุ่มไหนถึง) คำสั่ง typeof tasks[a] จะ return ‘undefined’ code ก็จะหยุดการทำงาน

อ่านเพิ่มเติม jQuery: Ajax รับข้อมูลแบบ stream