为什么需要多次调用Ajax?

我需要多次调用ajax才能写入linux中的命名管道,下面是我的代码。

Javascript和Ajax:

var count = 0;
var status = "online";

while(status=="online" && count!=25){

$.ajax({ url: 'http://192.168.5.10/Command.php',
         data: {cmd: 'GORIGHT'},
         type: 'post',
         success: function(data) {
                      console.log(data);
                  }
});

count++;
}

Command.php

if($_POST['cmd']==="GORIGHT"){

$fd = fopen("/tmp/myFIFO","w");
fwrite($fd, "GORIGHT
");
fclose($fd);
echo "SUCCESS";
}

这是正确的方法吗? 还是有更快的方法?会造成延迟吗?

If you need it to be synchronous, you will need to make sure that every calls are waiting completion of the previous one. Something like this should do the trick, untested thought:

var count=0;
var N=25;
loop();

function loop() {
    $.ajax({ url: 'http://192.168.5.10/Command.php',
        data: {cmd: 'GORIGHT'},
        type: 'post',
        success: function(data) {
            console.log(data);
        }
    })
    .done(function(data){
        if (count < N) {
            count++;
            loop();
        }
    });
}

Another idea (faster) could be to add an extra parameter in Command.php to allow you to specify how many time a predefined action must be done. You could have something like this instead:

var N=25;

$.ajax({ url: 'http://192.168.5.10/Command.php',
    data: {cmd: 'GORIGHT', repeat:N},
    type: 'post',
    success: function(data) {
        console.log(data);
    }
});