开发者

jquery ajax, I want to prevent form submit only if response = 200

开发者 https://www.devze.com 2023-01-17 08:04 出处:网络
doesn\'t work.. can\'t find any solution to prevent submit page reload only if ajax status is 200... $(\'form.insarticolo\').submit(function (e){

doesn't work.. can't find any solution to prevent submit page reload only if ajax status is 200...

$('form.insarticolo').submit(function (e){  
     function getUrlStatus(url, callback) {
    $.ajax({
        type: "POST",
        url : url,
        data: ({ testo : $('[name=testo]').val() }),
        da开发者_开发问答taType: "XML",
            success : function(xml) { $('label').find('span').hide();}
        complete: function(xhr) { callback(xhr.status); }
    });
}

getUrlStatus('http://www.website', function(status) {
    if (status == 200)  { 
                    e.preventDefault();
            }
});
}); 


The .submit() function can be canceled by returning false in the passed function. See http://api.jquery.com/submit/. An issue you may have is that the .ajax() function is asynchronous by default so it will return and processing will continue. To do what you are trying to do you will need to set the ajax mode to synchronous (async : false) so that you can wait for the response. Then you can check the status code to see if it is 200. If it is return false otherwise return true. I haven't tested this code but something like this

$('form.insarticolo').submit(function (e){ 
    var retStatus; 
    $.ajax({
        type: "POST",
        url : url,
        async : false,
        data: ({ testo : $('[name=testo]').val() }),
        dataType: "XML",
        complete: function(xhr) { retStatus = xhr.status; });

    if(retStaus == 200)
        return false;
    else
        return true;
});

NOTE: Synchronous requests with jQuery 1.4.2 cause memory issues in IE unless you cleanup the request in the callback function. After processing the xhr you should do the following:

xhr.onreadystatechange = null; xhr.abort = null; xhr = null;

This is documented at http://dev.jquery.com/ticket/6242


Try

$('form.insarticolo').submit(function (e){  
  if (!getUrlStatus('http://www.website'))
    $.ajax({
        type: "POST",
        url : url,
        data: ({ testo : $('[name=testo]').val() }),
        dataType: "XML",
            success : function(xml) { $('label').find('span').hide();}
        complete: function(xhr) { callback(xhr.status); }
    });
});

function getUrlStatus(url)
{
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}
0

精彩评论

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