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

Javascript 如何从字符串中获取数据集?,javascript,Javascript,请帮助携带一组数据。春天是: 我做了以下工作: 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); 结果是出现以下错误消息: 未捕获的语法错误:意外标记h 如果您试图

请帮助携带一组数据。春天是:

我做了以下工作:

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);
结果是出现以下错误消息:

未捕获的语法错误:意外标记h


如果您试图解析url而不是json,请仅使用本机js。您可以传递得到的响应,并使用
JSON对其进行解析。parse

var massive=JSON.parse('{“news”:[{“img”:”http://static1.smi2.net/img/160x120/2269036.jpeg“,”标题:“,网址:”http://news.smi2.ru/newdata/news?ad=696406&bl=81060&ct=adpreview&st=16&in=uU6IBQAiL4BWoAoA“,“id”:"696406"}]}');

console.log(massive.news[0].id);//输出696406
您无法从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();

JSON.parse
需要JSON,而不是URIS。请注意CORS限制。但我从中获取数据,您可以使用一个名为postmane的chrome扩展,并向以下url发出请求
http://news.smi2.ru/data/js/81060.js
。您得到的响应是您想要的
json
。请在我的答案中添加另一个示例。嘿,stackov8,这是jquery请求。如果您需要纯javascript,请参阅我的答案。@AlexChar cool work:-)
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();