如何使用纯javascript执行以下操作?

时间:2018-02-07 08:56:02

标签: javascript jquery

$.ajax({
  url: 'https://www.gravatar.com/avatar/71b0d516013802a2d67aeb7c2e77ed32?s=48&d=identicon&r=PG&f=1',
  success: function(r, s, x){ 
    var type = x.getResponseHeader("content-type");
    console.log(type); 
  }
});

这是为获取图像类型而编写的ajax请求。如何使用纯JavaScript进行相同操作?

1 个答案:

答案 0 :(得分:1)

使用JavaScript,您需要执行以下操作::

<script type="text/javascript">
function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
           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", "ajax_info.txt", true);
    xmlhttp.send();
}
</script>