Javascript无法在移动设备(Android)上运行,但在台式机上可以正常运行

时间:2020-02-18 20:44:36

标签: javascript android function mobile xmlhttprequest

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

在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的新手,发现编码回调函数和事件具有挑战性,但是我看不到任何明显的错误/原因使之在手机上失败。

我的工作是否存在已知问题或局限性?

有没有办法解决此问题或在移动设备上有效地对其进行调试?

请帮助!

谢谢

菲尔

1 个答案:

答案 0 :(得分:0)

因此,我尝试了各种尝试,发现问题出在使用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/

您生活和学习...

相关问题