javascript - 在 AJAX 成功响应中调用函数?

标签 javascript jquery ajax

我基本上是在尝试在 AJAX 成功响应中调用 AJAX 之外的函数。

为了更好地解释这一点,这就是我所拥有的。

这是两个函数:

function watchCurrentPosition() {
    var positionTimer = navigator.geolocation.watchPosition(function(position) {
        setMarkerPosition(userLocation, position);
        map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude)); 

    });

}

function clearmyWatch() { 

   navigator.geolocation.clearWatch(positionTimer);
}

其中一个持续监视用户位置,另一个“应该”停止监视。

这就是我在 AJAX 中调用 clearmyWatch(); 函数的方式:

$.ajax({
      type:"post",
      url:"TEST.PHP",
      datatype:"html",
      success:function(data)
      {
clearmyWatch();
      }
    });

但是,这不起作用,watchCurrentPosition(); 不断运行,并且我的控制台中也出现错误。

我收到的错误是这样的:

ReferenceError: positionTimer is not defined

有人可以就这个问题提出建议吗?

提前致谢。

最佳答案

您需要定义positionTimerfunction watchCurrentPosition() 之外的全局范围内像:

var positionTimer = null;

function watchCurrentPosition() {
     positionTimer = navigator.geolocation.watchPosition(function(position) {
        setMarkerPosition(userLocation, position);
        map.panTo(new google.maps.LatLng(position.coords.latitude, position.coords.longitude)); 

    });

}

function clearmyWatch() { 
    if(positionTimer)
        navigator.geolocation.clearWatch(positionTimer);
}

关于javascript - 在 AJAX 成功响应中调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40419732/

相关文章:

javascript - 构建应用程序后 Electron index.html 未加载

javascript - 类型错误 : t is undefined

javascript - Vue.js 多选来填充另一个多选

javascript - node.js:将数据插入 PostgreSQL 数据库时,HTML 表单在提交后挂起

javascript - jQuery - 如何使用parents()来访问1级和2级?

javascript - 单击 <img> 切换 Div 类

c++ - 如何在 Asp.Net AJAX UpdatePanel 之后获取文档 CDHtmlDialog

java - 如何修复firefox浏览器中的ajax调用,但在chrome浏览器中工作正常

ajax - Magento - 在当前模板设计中通过 ajax 加载产品

javascript - Bootstrap-tagsinput 中断 .input-group