【问题标题】:HTTP(S) Request With Javascript and receive JSON dataHTTP(S) 使用 Javascript 请求并接收 JSON 数据
【发布时间】:2015-09-21 13:18:17
【问题描述】:

由于我是 http(s) 请求案例的新手,我这里有一个案例必须用 Javascript 编写,希望有人可以帮助我,因为我到处搜索但找不到答案。情况如下:

但是,当连接速率上升到 5 时,我将不得不等到其中一个完成对应才能发送请求,以便其中 2 个或更多不超过 5。 另外,当响应码不是200时,我会重试3次。如果重试3次后响应码仍不是200,则错误函数会继续。我还必须接收响应体的 Json 数据作为参数函数。

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  else if (xmlhttp.readyState==4 && xmlhttp.status!=200){
    document.write("Error");
  }
}
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>

</body>
</html>

请在下面的评论中提供帮助,或者您可以向我推荐可以帮助我解决此案例的链接。谢谢。

【问题讨论】:

  • 你为什么没有在你的问题中包含代码,你到目前为止尝试了什么??
  • 抱歉,我已经在上面插入了我的代码,这就是我到目前为止所尝试的,我卡住了

标签: javascript json xmlhttprequest httprequest


【解决方案1】:

这样的?

关于连接速率,您可以使用它进行多个方向,因为它不是 100% 清楚您想要什么。最简单的解决方案是让您的 asp 页面将“假错误”作为 json 对象返回,并让 success 函数检查响应是否包含此“假错误”。如果是,则将请求重新发送到服务器。或者,如果连接率

var getJSON = function getJSON( resource, success, failure ) {
        var xmlhttp = (window.XMLHttpRequest) ? xmlhttp=new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
                retry = 0;
                success(xmlhttp.responseText, 200);
            }
            else failure(xmlhttp.status);
        }
        xmlhttp.open("GET", resource, true);
        xmlhttp.send();
    },
    retry = 0,
    success = function success( response, status ) {
        document.querySelector("#myDiv").textContent = response;    
    },
    failure = function failure( status ) {
        if (retry < 3) {
            retry += 1;
            getJSON("demo_get.asp", success, failure);
        }
        else console.log('ERROR');      
    };
document.querySelector('button').addEventListener('click', function( event ) {
    getJSON("demo_get.asp", success, failure);
});

【讨论】:

  • 感谢 Shilly 的建议,这非常有帮助,顺便说一句,您能否给我一个示例页面,以获取您所解释的响应?
  • 由于您期望的是 JSON 响应而不是 html 页面,因此只需返回数据的 JSON 结构。我对asp不熟悉,所以无法帮助你处理服务器端的问题。
  • 不不,asp 只是我的假设,如果你能帮助我提供 JSON 示例,那就太好了
  • 类似json = {"text":"contentThatNeedsToGoIntoTheDiv","error":false}json = {"text":false,"error":true}。然后可以将'success'函数改成:if (response.error) { ... } else { document.querySelector("#myDiv").textContent = response; }
猜你喜欢
  • 1970-01-01
  • 2013-09-29
  • 2014-02-24
  • 2014-07-26
  • 2017-06-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-30
相关资源
最近更新 更多