简体   繁体   English

无法使用 JSON API 获得响应

[英]Can't get response using JSON API

I was wondering what I was doing wrong with this code?我想知道我在这段代码中做错了什么? I'm trying to get the response for PC players from the API to be set to a我正在尝试从 API 中获取 PC 播放器的响应以设置为

tag in the html, but this isn't working. html 中的标记,但这不起作用。 Code:代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Battlefield 4 Tracker</title>

    <link href="css/bootstrap/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/jquery-3.1.1.min.js"></script>
</head>
<body>

<div id="fullscreen">
    <div class="fullscreen-content">
        <div id="centered">
            <h1>Battlefield 4 Stats Tracker</h1>
            <input id="username" name="username" placeholder="PSN Username">
            <button id="submit">Submit</button>
            <p id="response">
                Response goes here.
            </p>
        </div>
    </div>
</div>

<script>
    var request = new XMLHttpRequest();

    var jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)

    var obj = JSON.parse(jsonResponse);

    document.getElementById("response").innerHTML = obj.pc[1].count + "";
</script>

</body>
</html>

Since you are using JQuery as suggested by the html you provided , you can use $.get method of it.由于您按照您提供的 html 的建议使用 JQuery,因此您可以使用它的 $.get 方法。 This method is a simple wrapper to work with the xmlHTTP asynchronous calls.此方法是一个简单的包装器,用于处理 xmlHTTP 异步调用。 The success call back of this method is where you should populate the obj with response.此方法的成功回调是您应该用响应填充 obj 的地方。

And obj.pc is also an object, so you should access it like obj.pc.count而且 obj.pc 也是一个对象,所以你应该像 obj.pc.count 一样访问它

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Battlefield 4 Tracker</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" />

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
   <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>

</head>
<body>

<div id="fullscreen">
    <div class="fullscreen-content">
        <div id="centered">
            <h1>Battlefield 4 Stats Tracker</h1>
            <input id="username" name="username" placeholder="PSN Username">
            <button id="submit">Submit</button>
            <p id="response">
                Response goes here.
            </p>
        </div>
    </div>
</div>

<script>
    var request = new XMLHttpRequest();
    var obj = null;
     var jsonResponse = $.get("http://api.bf4stats.com/api/onlinePlayers", function(response){   
      obj = response;       
      document.getElementById("response").innerHTML = obj.pc.count + "";
    })



</script>

</body>
</html>

you forgot to send the XMLHttpRequest and what you get back is a object of object so you can call directly obj.pc.count.您忘记发送 XMLHttpRequest 并且您返回的是 object 的对象,因此您可以直接调用 obj.pc.count。 Try this one:试试这个:

var json = new XMLHttpRequest();

json.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
json.send(null)

var obj = JSON.parse(json.responseText);

document.getElementById("response").innerHTML = obj.pc.count;
  • The request is never send send();请求永远不会发送send();
  • The correct way to do this is to handle it in the onreadystatechange event.正确的做法是在onreadystatechange事件中处理它。

Try this (together with a proper check) :试试这个(连同适当的检查)

var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";

xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
        var obj = JSON.parse(this.responseText);
        myFunction(obj);
    }
};

xmlhttp.open("GET", url, true);
xmlhttp.send();


function myFunction(obj) {        
    document.getElementById("response").innerHTML = obj.pc.count;
}

or directly without extra function:或直接没有额外的功能:

var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";

xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
        var obj = JSON.parse(this.responseText);
        document.getElementById("response").innerHTML = obj.pc.count;
    }
};

xmlhttp.open("GET", url, true);
xmlhttp.send();

Demo演示

 var xmlhttp = new XMLHttpRequest(); var url = "http://api.bf4stats.com/api/onlinePlayers"; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var obj = JSON.parse(this.responseText); document.getElementById("response").innerHTML = obj.pc.count; } }; xmlhttp.open("GET", url, true); xmlhttp.send();
 <div id="response"></div>

You never sent the request.您从未发送过请求。 You're missing request.send().您缺少 request.send()。 You then listen for the load event, when you've gotten a response.然后,当您收到响应时,您将侦听 load 事件。

Here's an edited version of your code.这是您的代码的编辑版本。 I assumed that you want to loop through all the types of devices and count them.我假设您想遍历所有类型的设备并计算它们。

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="fullscreen"> <div class="fullscreen-content"> <div id="centered"> <h1>Battlefield 4 Stats Tracker</h1> <input id="username" name="username" placeholder="PSN Username"> <button id="submit">Submit</button> <p id="response"> Response goes here. </p> </div> </div> </div> <script> function reqListener () { //THIS HAPPENS AFTER THE REQUEST HAS BEEN LOADED. var obj = JSON.parse(this.responseText); var counter = 0; for(var k in obj) { var o = obj[k]; counter += o.count; } document.getElementById("response").innerHTML = counter; } var request = new XMLHttpRequest(); request.addEventListener("load", reqListener); request.open("GET", "http://api.bf4stats.com/api/onlinePlayers"); request.send(); </script> </body> </html>

You may want to consider other events such as a failed attempt to load the request, etc. Here's more info: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest您可能需要考虑其他事件,例如尝试加载请求失败等。这里有更多信息: https : //developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

Try this one :-试试这个:-

<script>
    var request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var obj = JSON.parse(this.responseText);
            document.getElementById("response").innerHTML = obj.pc.count + "";
        }
    };
    jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", true);
    request.send();
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM