Javascript获取URL的内容

时间:2014-10-05 12:00:55

标签: javascript

如果我输入此链接,我会在文本文件'f.txt'中获得“sun”一词的搜索建议数组

http://suggestqueries.google.com/complete/search?client=firefox&q=sun

如何仅使用此URL在Javascript中将其转换为数组?

2 个答案:

答案 0 :(得分:1)

您可以使用AJAX发出请求,然后使用JSON.parse将结果解析为JavaScript对象:

var req = new XMLHttpRequest();
req.onreadystatechange = function() {
    if (req.readyState === 4) {
        var response = req.responseText;
        var json = JSON.parse(response);

        console.log(json)
    }
};

req.open('GET', 'http://suggestqueries.google.com/complete/search?client=firefox&q=sun');
req.send(null);

答案 1 :(得分:0)

function httpGet(theUrl)
{
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            return xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", theUrl, false );
    xmlhttp.send();    
}