开发者

How to send data to server synchronously using JQuery?

I have to send some data to server in JQuery and I'm lost in a lot of functions like .ajax, .post, etc.

The conditions are very easy: a form must be sent synchronously, it won't return any value, but if there is an error we have to stop sending more data (really, I am sending a bunch of forms).

So, the question is: w开发者_StackOverflow中文版hich is the best function to do it and which are the minimum parameters I have to use?

At the moment, my approach is this:

            $.ajax({
                url: form.attr('action'),
                type: 'POST',
                data: form.serialize(),
                async: false,
            });

but as you can see, I'm not getting a return value if error.


How about calling asynchronously, but recursively:

var index = 0;
var data = ["some","data","chunks"];

function submit_data()
{
    if (index == data.length)
        return; //Done !

    index++;

    $.ajax({
        url: form.attr('action'),
        type: 'POST',
        data: data[index - 1],
        success: submit_data
    });
}

Each HTTP Request that doesn't return OK stops further data exchange (as the function is called again only on a HTTP status of 200 OK).


If you really want to do a synchronous post, you'll have to use ajax. I think this is the minimum (less if you don't care about success, or don't care about failure):

$.ajax({
    url: form.attr('action'),
    type: 'POST',
    data: form.serialize(),
    async: false,
    success: function(response) {
        // It worked (at the HTTP level). You could have the
        // server return something you can use for business
        // level success (or use an HTTP error code for errors);
        // if you return something, you can access it here as
        // `response`. (If not, you can remove that argument.)
    },
    error: function() {
        // It failed (at the HTTP level), so stop sending the
        // other forms.
    }
});

Off-topic 1: Your original script had a dangling comma at the end of the object literal. You want to avoid that, IE6 and IE7 don't like it.

Off-topic 2: Doing a synchronous ajax request is generally not your best option. Synchronous requests tend to completely lock up the UI of the browser while the request is happening (in some browsers, not just on your tab, but on every tab), making for a bad user experience. Instead, disable any inputs you have to disable, do the asynchronous request, and then re-enable things when the request completes. If you're sending a bunch of forms one after another, you can chain the requests, initiating the next request from the successful completion of the previous one.


This is a terrible idea. Since JavaScript is single threaded It would block all scripts from responding until the server returned. That would cause nothing in the UI to respond leading to unhappy users. Code to the model :)


Are you looking for basic HTTP errors? See T.J.'s answer. If you want the server to have some feedback you will need to receive some data back, and JSON works great for that.

function submitRating(object) {
            log.debug("will submit: " + object.html());
            log.profile("Rating Project");

            $.post("\+rate", {
                projectKey : "${projectDto.key}",
                rating : object.html()
            }, function(ratingDto) {
                log.debug("response recieved");
                if(ratingDto.duplicate){
                    $('#ratingMessage').html(ratingDto.message);
                    $('#ratingMessage').fadeIn(200).delay(800).fadeOut(200);
                }else{
                    $('#projectRating').html(ratingDto.rating);
                    $('#projectRatingCount').html(ratingDto.ratingCount);
                    $('.current-rating').css('width',''+(30 * ratingDto.rating)+'px');
                    $('.current-rating').html('Currently ' + ratingDto.rating + '/5');
                }
                log.profile("Rating Project");
            },'json');
        }


You can use sync call by setting async to false.

$.ajax({
    url: form.attr('action'),
    type: 'POST',
    data: form.serialize(),
    async: false
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜