如何从字符串中获取数据集

how to get the dataset from string?

本文关键字:获取 数据集 字符串      更新时间:2024-06-29

请帮忙带来一个数据数组。春天来了:

{"news": [{"img": "http://static2.smi2.net/img/160x120/2212764.jpeg", "title": "Усиление слуха в 2 - 3 раза! Уникальная разработка", "url": "http://news.smi2.ru/newdata/news?ad=681120&bl=81060&ct=adpreview&st=16&in=lJUrBQDHL4CgZAoA", "id": "681120"}]}

我做以下事情:

var massive = JSON.parse('http://news.smi2.ru/data/js/81060.js');
console.log(massive.news.id);
console.log(massive.news.img);
console.log(massive.news.title);
console.log(massive.news.url);

结果是以下错误消息:

未捕获的SyntaxError:意外的令牌h

仅使用本机js

您尝试解析url而不是json。您可以传递您得到的响应,并使用JSON.parse:进行解析

var massive = JSON.parse('{"news": [{"img": "http://static1.smi2.net/img/160x120/2269036.jpeg", "title": "Украинские власти и Саакашвили прокомментировали убийство Немцова", "url": "http://news.smi2.ru/newdata/news?ad=696406&bl=81060&ct=adpreview&st=16&in=uU6IBQAiL4BWoAoA", "id": "696406"}]}');
console.log(massive.news[0].id);//outputs 696406

为了清除它,你可以向你想要的url发出请求,例如使用ajax调用:

 $.ajax({
  url: "http://news.smi2.ru/data/js/81060.js",
  dataType : "json"
}).done(function(res) {
    console.log(res.news[0].id);//outputs 696463
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

您无法从url解析Json。如果您需要URI中的数据,请为此发送ajax调用:-//简单的javascript示例。

var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
     var massive = JSON.parse(xmlhttp.responseText);
console.log(massive.news[0].id);
console.log(massive.news[0].img);
console.log(massive.news[0].title);
console.log(massive.news[0].url);
    }
}
xmlhttp.open("GET","http://news.smi2.ru/data/js/81060.js",true);
xmlhttp.send();