Home How to receive data from json and store it into a variable?
Reply: 1

How to receive data from json and store it into a variable?

Travis Su
1#
Travis Su Published in 2017-12-07 23:08:27Z

I got a piece of code in here:

$.get("/upcase", {text: text})
.done((data) => {
    $('#results').prepend('<li>' + data['result'] + '</li>');
    $('#input').val(''); // reset the textbox
});

Usually the data data['result'] will be pass to a html <ul>tag with id="results" to form a list, but what if I want to store it into a variable, how do I achieve that?

At least it does not work like this:

let something = $('#results').val(data['result']);
andrewf
2#
andrewf Reply to 2017-12-07 23:12:20Z

declare a variable outside what you have, and in scope of where you need it. Say global. then just assign the data to it. i.e.

let globalResult;   
$.get("/upcase", {text: text})
  .done((data) => {
    globalResult = data;
    $('#results').prepend('<li>' + data['result'] + '</li>');
    $('#input').val('');   // reset the textbox
  })

just remember that data will be an object and get copied by reference, not value. So if you change data or globalData it will change the other. If that is no good you need to actually copy each element across.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.342088 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO