开发者

Polling AJAX request and sending data between javascript and server

I need to send a polling AJAX request to the server and send some data (which I think I'll just pass in the url) to the server. I'll have a number of different resque background jobs running, and I want to check if each job has finished. I found a gem to do that (resque-status), but I'm unsure how to send the data back-and-forth between the javascript and the controller.

The first thing is how would I construct this polling AJAX request to the serve开发者_开发百科r? What would the syntax be? The next thing I'm unsure about is how would I send the status of the job back to the ajax request, and then send the AJAX request back again if not all of the jobs are finished? I'm assuming JSON would probably help here.

I'd really appreciate code examples (preferably using Ruby on Rails and JQuery.


Use a library like jquery

js:

$(document).ready(function(){
    $.ajax({
        method: "POST",
        url: "ajax.php",
        dataType: "json", //jquery will convert the json into an object
        data: { //data sent to server
            foo: "foo",
            bar: "bar"
        },
        success: function(data){ //callback function
            if(data["type"] == "success"){
                alert(data["msg"]);
            }else{
                alert("malformed response");
            }
        }
    });
});

php:

<?php
$obj = new stdClass();
$obj->type = "success";
$obj->msg = "foo: " . $_POST["foo"] . ", bar: " . $_POST["bar"];
echo json_encode($obj); //echo the object as json
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜