【问题标题】:How to get json data from url with Cordova?如何使用 Cordova 从 url 获取 json 数据?
【发布时间】:2017-03-21 14:49:50
【问题描述】:

我开始使用 Cordova 为 android 开发应用程序,现在我正在谷歌搜索解决方案(白名单)以从 URL 获取 JSON 数据。但我找不到简单的教程。我发现的大多数教程对初学者都不太友好。我正在考虑尝试使用纯 javascript 获取 JSON 数据,但我认为这不是一个好主意。有没有一些简单的技巧或教程可以解决这个问题?我喜欢收到你的来信!

【问题讨论】:

标签: javascript android json cordova


【解决方案1】:

像这样?假设 hello.php 返回您的 JSON 数据。

    $.ajax({
        url: "yourwebsite.com/hello.php",
        type: 'GET',
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function (arr) {
            _getdata(arr);
        },
        error: function () {
            validationMsg();
        }
    });

function _getdata(arr){
   //your JSON resuls are now in arr. Do what you need with the array.
}

【讨论】:

    【解决方案2】:

    This example 可能会很有帮助。

    为了从服务器获取数据,你应该尝试 ajax 调用,jQuery 让它变得非常简单。这是示例中使用的从服务器加载数据的函数:

    function getEmployeeList() {
    $('#busy').show();
    $.getJSON(serviceURL + 'getemployees.php', function(data) {
        $('#busy').hide();
        $('#employeeList li').remove();
        employees = data.items;
        $.each(employees, function(index, employee) {
            $('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
                    '<img src="pics/' + employee.picture + '" class="list-icon"/>' +
                    '<p class="line1">' + employee.firstName + ' ' + employee.lastName + '</p>' +
                    '<p class="line2">' + employee.title + '</p>' +
                    '<span class="bubble">' + employee.reportCount + '</span></a></li>');
        });
        setTimeout(function(){
            scroll.refresh();
        });
    });
    

    }

    希望对你有帮助。

    【讨论】:

      【解决方案3】:
      fetch('/echo/json', {
        method: 'get'
      }).then((JSONresponse) => {
        // do whatever you want with your
        // JSONresponse here
      })
      

      【讨论】:

      • 虽然此代码可能会回答问题,但提供有关 如何 和/或 为什么 解决问题的附加 context 将改善答案的长度长期价值。提及为什么这个答案比其他答案更合适也没有什么坏处。
      猜你喜欢
      • 1970-01-01
      • 2014-03-13
      • 1970-01-01
      • 2022-12-22
      • 2019-11-22
      • 2015-09-06
      • 1970-01-01
      • 2016-01-18
      相关资源
      最近更新 更多