调用期间和出错时的Ajax

时间:2015-04-25 21:13:03

标签: jquery ajax

我有一个ajax调用,它获取用户的位置并从我的数据库中提取城市和省份。当您单击按钮以触发调用时,我希望输入框消失并替换为加载gif。

如果它无法返回任何内容,则该框应该返回。

我尝试过使用它:

    .ajaxStart(function(data) {
        $('#location').attr('disabled', 'disabled');
    })

但它阻止脚本做任何事情。

var x = document.getElementById("demo");

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } 
    else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

function showPosition(position) {
    var formData = {
        'latitude'              :  ''+ position.coords.latitude +'' ,
        'longitude'             : ''+ position.coords.longitude +'',
    };

    // process the form
    $.ajax({
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'php/includes/get_postal_rem.php', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'html', // what type of data do we expect back from the server
    })
    // using the done promise callback
    .done(function(data) {
            $('#location').val(data);
    });


    // stop the form from submitting the normal way and refreshing the page
    e.preventDefault();

}

1 个答案:

答案 0 :(得分:0)

添加函数以在//处理表单注释之前禁用输入框,例如

$('#location').attr('disabled', 'disabled');

// process the form comment. 

顺便说一下,你还需要添加代码来显示进度gif,并启用文本框并在你的ajax返回后隐藏这个gif(或者如果它出错了)

相关问题