调用一个网站,并使用javascript抓取文本


Call a website and grab text using javascript(api?)

我正在尝试使用这个网站:https://api.mojang.com/users/profiles/minecraft/[VARIABLE_HERE](以https://api.mojang.com/users/profiles/minecraft/Minecraftiscewl为例)

我想根据用户输入更改变量,并从页面抓取文本:

{" id ":"36 c84ed1708a4fc1b31e031bf1511de6"、"名称":"[TEXT_HERE]"}

我可以用javascript(以及如何)做到这一点,还是我需要使用PHP?

如何在没有jQuery的情况下进行AJAX调用?向您展示如何执行此操作。

基本上你对那个URL做一个XMLHTTPRequest,期望application/json作为接受类型。然后使用JSON将其拉入JS。parse将传入的数据转换为JS对象。然后你就可以正常地与它交互了。

<script type="text/javascript">
function loadXMLDoc() {
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 == XMLHttpRequest.DONE ) {
       if(xmlhttp.status == 200){
           document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
       }
       else if(xmlhttp.status == 400) {
          alert('There was an error 400')
       }
       else {
           alert('something else other than 200 was returned')
       }
    }
}
xmlhttp.open("GET", "https://api.mojang.com/users/profiles/minecraft/[VARIABLE_HERE]", true);
xmlhttp.send();

}

有许多与XMLHTTPRequest对象交互的方法(参见:https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)。或者,如果您已经为其他目的加载了jQuery,您也可以使用答案中所述的jQuery。

JSON.parse()调用产生的对象将恰好是您发布的JSON,因此您可以这样做:

var playerData = JSON.parse(dataFromAjaxCall);
console.log(playerData.name); //[TEXT_HERE]