0

在移动设备上使用我的代码时遇到错误(PC 处理时间更快不会出现问题)。我怀疑我遇到的问题与未按顺序触发的函数有关——即即使未设置所有参数,它们仍会继续执行。

基本前提是调用JQuery Geolocation,将经纬度数据与通过onClick函数传递的参数配合使用。然后将其传递到 AJAX,然后返回基于此数据的结果。

然而,在移动设备上进行测试时,有时当您单击链接时,GPS 不会及时触发,但仍会继续。结果是什么都没有回来,用户面临着一个空白屏幕。如果您给它足够的时间并单击足够多的时间,它将起作用。这并不总是发生,但似乎并非所有数据都已准备好。

我尝试了许多变体,但由于我只是一个中级 JS 编码器,我无法找出问题所在。喜欢一些反馈!

if(navigator.geolocation) {/* Function for returning list of locations for a unique cuisine */
    function locationList(clicked_id) {
        navigator.geolocation.getCurrentPosition(
            function(position) { 
                $.ajax({
                    url: 'search.php',
                    type: 'GET',
                    data: 'id=' + clicked_id + '&action=geolocation&latitude=' + position.coords.latitude + '&longitude=' + position.coords.longitude,
                    beforeSend: function () {
                        $('#location-list').html('<div class="ajax-load"><img src="img/ajax-loader.gif" /></a>');
                    },
                    success: function (msg) {
                        $('#location-list').html(msg);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {   
                        alert('Error submitting request.'); 
                    }
                });
            }, /* position */
            function() {
                $('#location-list').html('<div class="toolbar"><h1>GPS Error</h1><a class="back" href="#home">Home</a></div><div class="scroll"><ul class="rounded"><li><p>To take advantage of this app you need the GPS capability of your phone turned on. Please check whether this is turned on or else the app will not work</p></li></ul></div>');
            } /* no position so failure */
        );
    } /* locationList */
}/* navigator.geolocation */
4

1 回答 1

1

与其说是自定义函数的顺序(通常会以串行方式执行),不如说是内部 API;在这种情况下,$.ajax。默认情况下,Ajax 调用是异步的,因此函数的其余部分将继续进行,而不关心响应。

要等待响应,请将参数添加async: false到您的 Ajax 调用中。

[编辑添加:] 根据 jfriend00 的评论,这将导致糟糕的用户体验。我无意为他重新设计 OP 的方法,但同时我不想暗示认可通过使用 WITH async 可以大大改进设计。

于 2012-03-24T02:44:05.587 回答