首页 > 解决方案 > 没有从 axios 获得 json 输出

问题描述

我正在使用 axios 从 Wikipedia Api 检索数据。这是我写的代码。

let axiosData = function(){
let searchString = $('#searchString').val();
console.log(searchString);
let Url = "https://en.wikipedia.org/w/api.php?action=opensearch&search="+ searchString + 
"&origin=*&callback=";
axios.get(Url)
 .then(function(res){
     var linkLists = res.data;
     console.log(linkLists);
 })
 .catch(function(){
     console.log("Error")
 });
return false;
}

$('form').submit(axiosData);

当我控制台记录它时,我能够得到一个输出。以下是:在这种情况下,我正在搜索 Jon Snow 的名字。如何访问json?

/**/(["jon snow",["Jon Snow (character)","Jon Snow (journalist)","Jon Snow","John Snow (cricketer)","Jon Snoddy","John Snow","Jon Snodgrass (musician)","Jon Snodgrass","John Snow College, Durham","John Snow, Inc"],["Jon Snow is a fictional character in the A Song of Ice and Fire series of fantasy novels by American author George R. R.","Jonathan George Snow HonFRIBA (born 28 September 1947) is an English journalist and television presenter.","Jon Snow may refer to:","John Augustine Snow (born 13 October 1941) is a retired English cricketer. He played for Sussex and England in the 1960s and 1970s.","Jon Snoddy is an American technology expert who is currently the Advanced Development Studio Executive SVP at Walt Disney Imagineering.","John Snow (15 March 1813 \u2013 16 June 1858) was an English physician and a leader in the  development of  anaesthesia and medical hygiene.","Jon Snodgrass is \"the guy with the glasses from Drag the River\".","Jon Snodgrass is a Panamanian author, born on July 27, 1941 in Col\u00f3n, Panama to John Alphonso and Olivia Jane (Chestnut) Snodgrass.","John Snow College is one of 16 constituent colleges of the University of Durham in England. The College takes its name from the nineteenth-century Yorkshire physician Dr John Snow.","John Snow, Inc. (JSI) is a public health research and consulting firm in the United States and around the world."],["https://en.wikipedia.org/wiki/Jon_Snow_(character)","https://en.wikipedia.org/wiki/Jon_Snow_(journalist)","https://en.wikipedia.org/wiki/Jon_Snow","https://en.wikipedia.org/wiki/John_Snow_(cricketer)","https://en.wikipedia.org/wiki/Jon_Snoddy","https://en.wikipedia.org/wiki/John_Snow","https://en.wikipedia.org/wiki/Jon_Snodgrass_(musician)","https://en.wikipedia.org/wiki/Jon_Snodgrass","https://en.wikipedia.org/wiki/John_Snow_College,_Durham","https://en.wikipedia.org/wiki/John_Snow,_Inc"]])

标签: jsonapiaxiosmediawiki

解决方案


在 json 的开头有 '/**/(' 和结尾的 ')' 字符,它们被子字符串剪切。解析之后。

let Url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=jon%20snow&origin=*&callback=";
axios.get(Url)
.then(function(res){
 console.log(res);
 var linkLists = JSON.parse(res.data.substring(5, res.data.length-1));
 console.log(linkLists)
 })
 .catch(function(){
   console.log("Error...")
 });

推荐阅读