【问题标题】:Javascript not working on mobile (Android) but fine on desktopJavascript 无法在移动设备 (Android) 上运行,但在桌面上运行良好
【发布时间】:2020-06-02 23:05:49
【问题描述】:

我搜索了档案,但没有找到任何特定于我的查询的内容。

在 JavaScript 中,我有一个带有回调函数的函数,该函数在邮政编码 API 处触发请求以获取邮政编码的坐标。

const getPostCodeLatLng = (strPostCode, callback) => {
    alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
    const request = new XMLHttpRequest();
    request.addEventListener('readystatechange', () => {
        if(request.readyState == 4){
            const jsnPostCode=JSON.parse(request.responseText);
            callback(jsnPostCode);}});
    request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);
    request.send();
};

getPostCodeLatLng(strInputFieldValue, (jsnPostCode) => { // use the function to get data about the postcode and callback to this function
            if(jsnPostCode.status=="match"){
                alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
                let strPostCodeLatLng = "LatLng(" + jsnPostCode.data.latitude + ", "
                + jsnPostCode.data.longitude + ")";
                setFieldswithLatLng(strPostCodeLatLng);
                objDisplayFindCons.value=`Postcode: ${strInputFieldValue}`;}
            else objDisplayFindCons.value=`No match found for Postcode: ${strInputFieldValue}`;})

这些功能在台式机上运行良好,但在三星手机或平板电脑上均无法运行。我在所有设备上都使用 Chrome。

第二部分代码是较大部分的一部分,它响应将数据输入到文本框中的事件,验证为可能的邮政编码(使用正则表达式),然后根据第一个函数请求。然后解析并检查 JSON 文本响应以查看是否找到匹配项(服务器为未找到的邮政编码返回有效的 JSON)。
我很清楚,在遇到函数调用 getPostCodeLatLng() 之前一切正常,它从未在移动设备上运行任何 alert("used API") 语句。

我是 JavaScript 新手,发现编码回调函数和事件具有挑战性,但我看不出有任何明显的错误/原因导致这在移动设备上失败。

我正在做的事情是否存在已知问题或限制?

有没有办法解决这个问题或在移动设备上有效地调试它?

请帮忙!

谢谢,

菲尔

【问题讨论】:

    标签: javascript android function mobile xmlhttprequest


    【解决方案1】:

    所以我尝试了各种方法,发现问题在于使用 http 请求。

    显然,从现在开始,来自 Android 上 Chrome 浏览器的所有请求都必须是 https

    所以改变request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);request.open('GET', 'https://api.getthedata.com/postcode/' + strPostCode); 直接解决了问题。

    这里有一篇文章提到了这个变化:-
    https://www.thesslstore.com/blog/https-will-now-be-the-default-for-all-android-p-apps/

    你生活和学习......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多