Js脚本可在台式机上使用,但不能在移动设备上使用

时间:2020-10-23 15:22:41

标签: javascript html

因此js代码是从本地api获取json数据并以表格格式显示数据,所有内容都可以在桌面上运行,但在移动设备上则不显示任何数据。我尝试了一切,但是此js代码出了点问题。

我不明白这是什么问题,HTML页面的其余部分在移动设备上的加载情况都很好。我应该在代码中进行任何更改。


function getUrl(start = 0) {
    return 'http://localhost/login_registration_system_LAMP/api.php';
}
function getData(url) 
{
    fetch(url)
        .then(response => response.json())
        .then(data => loadDataIntoTable(data))
        .catch(err => console.log(err));
}

function loadDataIntoTable(data) {
    let coinprodName = [];
    let coinprice = [];
    let coinper = [];
    let coinPerson = [];
    let coinphone = [];
    let coinsize = [];
    let coinbrand = [];
    let coinspecial = [];
    let coinlife = [];
    let coinmoq = [];

    data.forEach((coin) => {
        coinprodName.push(coin.product_name);
        coinprice.push(coin.price);
        coinper.push(coin.per);
        coinPerson.push(coin.person_name);
        coinphone.push(coin.phone);
        coinsize.push(coin.size);
        coinbrand.push(coin.brand);
        coinspecial.push(coin.special);
        coinlife.push(coin.life);
        coinmoq.push(coin.moq);
    });

    let tableBody = document.getElementById('crypto-table-body');

    let html = "";

    for(let i = 0; i < coinmoq.length; i++) {
        html += "<tr>";
        html += "<td>" + coinprodName[i] + "</td>";
        html += "<td>" + coinprice[i] + "</td>";
        html += "<td>" + coinper[i] + "</td>";
        html += "<td>" + coinPerson[i] + "</td>";
        html += "<td>" + coinphone[i] + "</td>";
        html += "<td>" + coinsize[i] + "</td>";
        html += "<td>" + coinbrand[i] + "</td>";
        html += "<td>" + coinspecial[i] + "</td>";
        html += "<td>" + coinlife[i] + "</td>";
        html += "<td>" + coinmoq[i] + "</td>";
        
        
        html += "</tr>";
    }

    tableBody.innerHTML = html;
}

function init() {
    const url = getUrl();
    getData(url);
}

init();

screenshot of phone and desktop

screenshot of phone and desktop

2 个答案:

答案 0 :(得分:2)

这是因为您在移动设备上使用localhost,所以使用了类似的https://ngrok.com/

localhost是一个主机名,它引用用于访问它的当前计算机。因此,在您的手机上,没有localhost

安装后,您可以按照以下方式使用ngrok

ngrok http 80

答案 1 :(得分:0)

制造服务器并从其他设备上使用服务器时,请使用192.168.1.X之类的内部ip来指出。

示例: 在使用台式机和手机的同一网络中,台式机具有内部IP 192.168.1.2,而您拨打的电话是192.168.1.3

因此,当您使用getUrl函数时:

function getUrl(start = 0) {
    return 'http://192.168.1.2/login_registration_system_LAMP/api.php';
}

如果您的电话不在同一个网络中,那么,您需要使用其他工具,例如“ noIp”,ngrok等。

提示:

CORS呢? 好吧,如果您不发送cors标头,则您的电话将无法使用您的API。 请检查以下内容:

 header("Access-Control-Allow-Origin: *");