AJAX Get from JSON Tree

I am just starting with AJAX, trying to use the jQuery function $ .getJSON (or any related ones, i.e. $ .load (), $ .ajax (), etc.). I have a JSON file with a structure something like this:

[
    {
        "id": 1,
        "email": "user@domain.com",
        "password": "password"
    },
    {
        "id": 2,
        "email": "one@two.com",
        "password": "password"
    }
]

How can I call GET in this JSON file (call him user.json) for a user with a specific email? I thought this would be the second parameter in $ .getJSON, but it seems to just return the whole tree.

Thanks!

0
source share
3 answers

The short answer is you cannot do this directly with AJAX. jQuery can extract parts of HTML and XML documents, but not JSON.

- ( , ) jsonpath,

- ,

- , script json .

+2

JSON - , .

, - :

$.getJSON(myURL, function(data) {
    /* data is an array of objects */
    for (var i=0, j=data.length; i<j; i++) {
        if (data[i].email === some_value) {
            /* do something with data[i] */
        };
    };
});

http://api.jquery.com/jQuery.getJSON/

+1

1 2 , user.json ( , php)

json

JS

$.ajax({
   url:"/users.json.php",
   data:{
      useremail:"someusersemail@here.com"
   }
   type:"POST",
   dataType:"json",
   success:function(userdata){
      //users data will be in userdata
      console.log(userdata.email);
   }
})

Script ( PHP): users.json.php

$email = $_POST['useremail'];

//get user data based on email
...

echo json_encode($userdata);
die;

json -

{"id": 1,"email": "user@domain.com","password": "password"}

Loop:

$.ajax({
   url:"/users.json",
   dataType:"json",
   success:function(data){
      for(i=0;i<data.length;i++) {
         var user = data[i];
         if(user.email == "someemail@gmail.com") {
            //do what you need to with user data
         }
      }
   }
})
+1
source

Source: https://habr.com/ru/post/1526818/


All Articles