Ajax get request for a json file using jquery

时间:2017-06-15 09:28:42

标签: javascript jquery json ajax

I am new to jQuery and Ajax and im trying to use jQuery and ajax to make a request for a JSON FILE. This is the stucture.

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  }
]

I want to put this into an array of objects. My code is this

 $("button").click(function(){
    $.get("https://jsonplaceholder.typicode.com/todos", function(data, status){
        array=JSON.parse(data);
           join();
           render();

    });
});

That doesnt work but this does

 var xhttp= new XMLHttpRequest();
 xhttp.onreadystatechange=function()
 {
  //console.log(this.readyState+" "+this.status);
  if(this.readyState==4&&this.status==200)
  {
     array=JSON.parse(this.response);

        join();
        render();


  }
 }
 xhttp.open("GET","https://jsonplaceholder.typicode.com/todos",true);
 xhttp.send();

3 个答案:

答案 0 :(得分:1)

Use $.getJSON() instead of $.get() like below:-

$.getJSON( "https://jsonplaceholder.typicode.com/todos", function( data ) {

  console.log(data);//check data coming properly or not 

  //do rest of the coding accordingly
});

答案 1 :(得分:0)

This would populate the myObjects array, with the objects coming in the JSON.

let myObjects = [];    
$("button").click(function(){
        $.get("https://jsonplaceholder.typicode.com/todos", function(data, status){
        array=JSON.parse(data);
        if(response)
        {
        data.forEach(function (obj) {
           myObjects.push(obj)
        })

           join();
           render();
        }
        else {
           response=true;
        }
    });
});

答案 2 :(得分:0)

Here there's no need to check response for 2 reasons:

  1. There's no argument with this name passed by $.get.
  2. The function, in which the code is, is a success callback. So you are sure to have a succesful response and your data is present.

So you could write your code like this:

$("button").click(function(){
    $.get("https://jsonplaceholder.typicode.com/todos", function(data, status){
        array=JSON.parse(data);
        join();
        render();
    });
});

If the data is already in JSON, you don't need to call JSON.parse:

$("button").click(function(){
    $.get("https://jsonplaceholder.typicode.com/todos", function(data, status){
        join();
        render();
    });
});