将 Json 保存在 Javascript 变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11116760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Save Json in Javascript variable
提问by user1453638
I'm studying javascript these days and I have question. I have variable that contain an url. I would like to save the content of the url pointed by my variable in another variable...
这些天我正在学习 javascript 并且我有问题。我有一个包含 url 的变量。我想将我的变量指向的 url 的内容保存在另一个变量中...
The first variable is something like:
第一个变量是这样的:
var Link = "http://mysite.com/json/public/search?q=variabile&k=&e=1";
If I open the link I see something like:
如果我打开链接,我会看到如下内容:
{
"count": 1,
"e": 1,
"k": null,
"privateresult": 0,
"q": "gabriel",
"start": 0,
"cards": [
{
"__guid__": "cdf8ee96538c3811a6a118c72365a9ec",
"company": false,
"__title__": "Gabriel Butoeru",
"__class__": "entity",
"services": false,
"__own__": false,
"vanity_urls": [
"gabriel-butoeru"
]
}
]
}
How can I save the json content in another javascript variable?
如何将 json 内容保存在另一个 javascript 变量中?
回答by UltraInstinct
You would need a simple AJAX request to get the contents into a variable.
您需要一个简单的 AJAX 请求来将内容放入一个变量中。
var xhReq = new XMLHttpRequest();
xhReq.open("GET", yourUrl, false);
xhReq.send(null);
var jsonObject = JSON.parse(xhReq.responseText);
Please note that AJAX is bound by same-origin-policy, in case that URL is different this will fail.
请注意,AJAX 受same-origin-policy约束,如果 URL 不同,这将失败。
回答by Miqdad Ali
You can use like this
你可以这样使用
var savings_data = JSON.stringify(your_json_object);
回答by Neo Generation
I think this might help you, using jQuery... :)
我认为这可能会帮助你,使用 jQuery ... :)
$.ajax({
beforeSend: function() { DO HERE WHATEVER }, //Show spinner
complete: function() { DO HERE WHATEVER }, //Hide spinner
type: 'POST',
url: Link,
dataType: 'JSON',
success: function(data){
var data = data;
OR IF YOU WANT SEPARATE THE VALUES...
var count = data.count;
var e = data.e;
var k = data.k;
...
}
});
回答by Sam T
回答by Rex CoolCode Charles
This example considers the state of the request and will allow you to access the data from the JSON format using the dot operator.
此示例考虑了请求的状态,并允许您使用点运算符访问 JSON 格式的数据。
var request = new XMLHttpRequest();
request.open("GET", "mysite.com/json/public/search?q=variabile&k=&e=1", true);
request.setRequestHeader("Content-type", "application/json");
request.send();
request.onreadystatechange = function(){
if(request.ready == 4 && request.readyState == 200){
var response = request.responseText;
var obj = JSON.parse(response);
alert(obj.count); // should return the value of count (i.e Count = 1)
alert(obj.e); // should return the value of e (i.e. e = 1)
var count = obj.count; //store the result of count into your variable
var e = obj.e; //store the result of e into your variable
//...and so on
}
}