简体   繁体   English

如何从json接收数据并将其存储到变量中?

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

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? 通常,数据data['result']将被传递到id="results"的html <ul>标记中以形成列表,但是如果我想将其存储到变量中怎么办?

At least it does not work like this: 至少它不能这样工作:

let something = $('#results').val(data['result']);

declare a variable outside what you have, and in scope of where you need it. 在您拥有的变量之外以及您需要的范围内声明一个变量。 Say global. 说全球。 then just assign the data to it. 然后将数据分配给它。 ie

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. 因此,如果您更改数据或globalData,它将更改另一个。 If that is no good you need to actually copy each element across. 如果那不好,则需要实际复制每个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM