如何合并两个不同的URL以使用jquery进行解析

问题描述 投票:0回答:2

我想尝试使用两个不同的URL进行解析,但是我的代码无法正常工作:我尝试了两个不同的示例:

   var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";

$.when($.getJSON(url), $.getJSON(url2)).done(function (data1, data2) {

    alert(data1.address.village);
    alert(data2.address.city);

    //do stuff with 'data' and 'data2'
});


$.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data) {
    $.getJSON("https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311", function (data2) {
        var concatenatedJson = $.extend({}, data, data2);

        alert(concatenatedJson.address.road);

    });
});
jquery json parsing getjson
2个回答
0
投票

您唯一的错误是假设您正在接收的数据

一个简单的console.log(data1)足以告诉您,data1中接收的数据不是来自URL的数据,而是一个包含更多信息的数组

enter image description here您所需要做的就是指向正确的数组,所有这些都将按您的意愿工作:

var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";

$.when($.getJSON(url), $.getJSON(url2)).done(function (data1, data2) {

    alert(data1[0].address.village);
    alert(data2[0].address.city);

    //do stuff with 'data' and 'data2'
});

-1
投票
var url = "https://nominatim.openstreetmap.org/reverse.php?zoom=15&format=json&lat=45.9660047&lon=13.6408311";
var url2 = "https://nominatim.openstreetmap.org/reverse.php?zoom=18&format=json&lat=45.9660047&lon=13.6408311";


var data = {};

$.getJSON(url, function(result){
  data.data1 = result;
});

$.getJSON(url2, function(result){
  data.data2 = result;
});


console.log(data); // will return the two urls json code

您可以尝试使用jsfiddle(https://jsfiddle.net/qtcvux31/)上的代码

© www.soinside.com 2019 - 2024. All rights reserved.