Hướng dẫn html get json data from url - html lấy dữ liệu json từ url

Tôi có một tài nguyên bên ngoài tương tự như //www.googleapis.com/freebase/v1/text/en/bob_dylan trả về JSON. Tôi muốn hiển thị giá trị của khóa kết quả trong DIV trong HTML [giả sử tên của Div là "Tóm tắt"]. Ngoài ra giá trị của phím kết quả phải được hiển thị trong văn bản thuần túy. URL trả về JSON:
The URL returns the json:

{"Kết quả": "Bob Dylan, sinh ra Robert Allen Zimmerman, là một ca sĩ-nhạc sĩ người Mỹ, tác giả, nhà thơ và họa sĩ, người đã là một nhân vật chính trong âm nhạc nổi tiếng trong năm thập kỷ. Những năm 1960, khi anh trở thành một ....... "}

JSON chỉ có khóa kết quả, không có khóa nào khác về cơ bản tôi không muốn sử dụng bất cứ thứ gì khác ngoài HTML và JavaScript đơn giản. Tôi là người mới bắt đầu với JavaScript và do đó tôi yêu cầu mã nhận xét.
Basically I do not want to use anything other than plain HTML and JavaScript. I am a relative beginner to JavaScript and therefore I ask for commented code.

hỏi ngày 29 tháng 3 năm 2012 lúc 8:56Mar 29, 2012 at 8:56

2

Đây là một không sử dụng jQuery với JavaScript thuần túy. Tôi đã sử dụng lời hứa của JavaScript và xmlhttprequest bạn có thể dùng thử ở đây trên fiddle này

HTML

JavaScript

var getJSON = function[url] {
  return new Promise[function[resolve, reject] {
    var xhr = new XMLHttpRequest[];
    xhr.open['get', url, true];
    xhr.responseType = 'json';
    xhr.onload = function[] {
      var status = xhr.status;
      if [status == 200] {
        resolve[xhr.response];
      } else {
        reject[status];
      }
    };
    xhr.send[];
  }];
};

getJSON['//www.googleapis.com/freebase/v1/text/en/bob_dylan'].then[function[data] {
    alert['Your Json result is:  ' + data.result]; //you can comment this, i used it to debug

    result.innerText = data.result; //display the result in an HTML element
}, function[status] { //error detection....
  alert['Something went wrong.'];
}];

b4hand

9.2754 huy hiệu vàng44 Huy hiệu bạc49 Huy hiệu đồng4 gold badges44 silver badges49 bronze badges

Đã trả lời ngày 5 tháng 7 năm 2014 lúc 14:43Jul 5, 2014 at 14:43

6

Bạn có thể làm điều này với JSONP như thế này:

function insertReply[content] {
    document.getElementById['output'].innerHTML = content;
}

// create script element
var script = document.createElement['script'];
// assing src with callback name
script.src = '//url.to.json?callback=insertReply';
// insert script to document and load content
document.body.appendChild[script];

Nhưng nguồn phải nhận thức được rằng bạn muốn nó gọi chức năng được truyền dưới dạng tham số gọi lại cho nó.

Với Google API, nó sẽ trông như thế này:

function insertReply[content] {
    document.getElementById['output'].innerHTML = content;
}

// create script element
var script = document.createElement['script'];
// assing src with callback name
script.src = '//www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply';
// insert script to document and load content
document.body.appendChild[script];

Kiểm tra xem dữ liệu trông như thế nào khi bạn chuyển cuộc gọi lại cho Google API: //www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertreply

Đây là lời giải thích khá tốt về JSONP: //en.wikipedia.org/wiki/jsonp

Đã trả lời ngày 29 tháng 3 năm 2012 lúc 9:13Mar 29, 2012 at 9:13

XavierxavierXavier

2742 Huy hiệu bạc3 Huy hiệu đồng2 silver badges3 bronze badges

0

Vì đó là tài nguyên bên ngoài mà bạn cần phải đi với JSONP vì chính sách gốc tương tự. Để làm điều đó, bạn cần thêm tham số QueryString

var getJSON = function[url] {
  return new Promise[function[resolve, reject] {
    var xhr = new XMLHttpRequest[];
    xhr.open['get', url, true];
    xhr.responseType = 'json';
    xhr.onload = function[] {
      var status = xhr.status;
      if [status == 200] {
        resolve[xhr.response];
      } else {
        reject[status];
      }
    };
    xhr.send[];
  }];
};

getJSON['//www.googleapis.com/freebase/v1/text/en/bob_dylan'].then[function[data] {
    alert['Your Json result is:  ' + data.result]; //you can comment this, i used it to debug

    result.innerText = data.result; //display the result in an HTML element
}, function[status] { //error detection....
  alert['Something went wrong.'];
}];
0:
To do that you need to add the querystring parameter
var getJSON = function[url] {
  return new Promise[function[resolve, reject] {
    var xhr = new XMLHttpRequest[];
    xhr.open['get', url, true];
    xhr.responseType = 'json';
    xhr.onload = function[] {
      var status = xhr.status;
      if [status == 200] {
        resolve[xhr.response];
      } else {
        reject[status];
      }
    };
    xhr.send[];
  }];
};

getJSON['//www.googleapis.com/freebase/v1/text/en/bob_dylan'].then[function[data] {
    alert['Your Json result is:  ' + data.result]; //you can comment this, i used it to debug

    result.innerText = data.result; //display the result in an HTML element
}, function[status] { //error detection....
  alert['Something went wrong.'];
}];
0:

$.getJSON["//myjsonsource?callback=?", function[data] {
    // Get the element with id summary and set the inner text to the result.
    $['#summary'].text[data.result];
}];

Đã trả lời ngày 29 tháng 3 năm 2012 lúc 9:05Mar 29, 2012 at 9:05

2

Nếu bạn muốn sử dụng JavaScript đơn giản, nhưng tránh những lời hứa, bạn có thể sử dụng giải pháp của Rami Sarieddine, nhưng thay thế lời hứa bằng chức năng gọi lại như thế này:

var getJSON = function[url, callback] {
    var xhr = new XMLHttpRequest[];
    xhr.open['get', url, true];
    xhr.responseType = 'json';
    xhr.onload = function[] {
      var status = xhr.status;
      if [status == 200] {
        callback[null, xhr.response];
      } else {
        callback[status];
      }
    };
    xhr.send[];
};

Và bạn sẽ gọi nó như thế này:

getJSON['//www.googleapis.com/freebase/v1/text/en/bob_dylan', function[err, data] {
  if [err != null] {
    alert['Something went wrong: ' + err];
  } else {
    alert['Your Json result is:  ' + data.result];
    result.innerText = data.result;
  }
}];

Đã trả lời ngày 13 tháng 3 năm 2016 lúc 13:22Mar 13, 2016 at 13:22

Robin Hartmannrobin HartmannRobin Hartmann

2.0191 Huy hiệu vàng14 Huy hiệu bạc25 Huy hiệu đồng1 gold badge14 silver badges25 bronze badges

2

Bạn có thể sử dụng cuộc gọi $ .AJAX để lấy giá trị và sau đó đặt nó vào Div mà bạn muốn. Một điều bạn phải biết là bạn không thể nhận được dữ liệu JSON. Bạn phải sử dụng JSONP.

Mã sẽ như thế này:

function CallURL[]  {
    $.ajax[{
        url: '//www.googleapis.com/freebase/v1/text/en/bob_dylan',
        type: "GET",
        dataType: "jsonp",
        async: false,
        success: function[msg]  {
            JsonpCallback[msg];
        },
        error: function[]  {
            ErrorFunction[];
        }
    }];
}

function JsonpCallback[json]  {
    document.getElementById['summary'].innerHTML = json.result;
}

Đã trả lời ngày 29 tháng 3 năm 2012 lúc 9:30Mar 29, 2012 at 9:30

1

Để hiển thị dữ liệu JSON bằng mã Robin Hartman. Bạn cần thêm, dòng dưới đây.Robin Hartman code. You need to add, the below line.

Mã anh ấy đưa ra cho bạn đối tượng, đối tượng. Mã này lấy dữ liệu theo cách tốt hơn.

result.innerText =JSON.stringify[data];

Đã trả lời ngày 14 tháng 3 năm 2017 lúc 14:40Mar 14, 2017 at 14:40

1

Vì trang mong muốn sẽ được gọi từ một miền khác, bạn cần trả lại JSONP thay vì JSON.jsonp instead of a json.

$.get["//theSource", {callback : "?" }, "jsonp",  function[data] {
    $['#summary'].text[data.result];
}];

Đã trả lời ngày 29 tháng 3 năm 2012 lúc 9:06Mar 29, 2012 at 9:06

Nicola Peluchettinicola PeluchettiNicola Peluchetti

75.3K30 Huy hiệu vàng138 Huy hiệu bạc191 Huy hiệu Đồng30 gold badges138 silver badges191 bronze badges

0

Chúng ta có thể đọc dữ liệu JSON trực tiếp từ dịch vụ web qua HTTP không?

JSON Web Services cho phép bạn truy cập các phương thức dịch vụ cổng thông tin bằng cách hiển thị chúng dưới dạng API JSON HTTP.Các phương thức dịch vụ được thực hiện dễ dàng bằng cách sử dụng các yêu cầu HTTP, cả từ JavaScript trong cổng thông tin và từ bất kỳ máy khách nói tiếng JSON nào.. Service methods are made easily accessible using HTTP requests, both from JavaScript within the portal and from any JSON-speaking client.

Làm thế nào tôi có thể lấy dữ liệu từ JSON?

Bất kỳ dữ liệu JSON nào cũng có thể được tiêu thụ từ các nguồn khác nhau như tệp JSON cục bộ bằng cách tìm nạp dữ liệu bằng cách sử dụng cuộc gọi API.Sau khi nhận được phản hồi từ máy chủ, bạn cần hiển thị giá trị của nó.Bạn có thể sử dụng các tệp JSON cục bộ để thực hiện cấu hình ứng dụng, chẳng hạn như Quản lý URL API dựa trên môi trường máy chủ như Dev, QA hoặc Prod.fetching the data using an API call. After getting a response from the server, you need to render its value. You can use local JSON files to do an app config, such as API URL management based on a server environment like dev, QA, or prod.

Làm thế nào lấy dữ liệu JSON từ tìm nạp?

Để lấy JSON từ máy chủ bằng API tìm nạp, bạn cần sử dụng phương thức JavaScript Fetch []. Sau đó, bạn cần gọi phương thức Phản hồi.json [] để lấy JSON.Tiêu đề "Chấp nhận: Ứng dụng/JSON" cho máy chủ biết rằng máy khách mong đợi phản hồi JSON.use the JavaScript fetch[] method. Then you need to call the response. json[] method to get the JSON. The "Accept: application/json" header tells the server that the client expects a JSON response.

Chủ Đề