在页面上未调用window.onload函数

时间:2018-07-21 06:57:29

标签: javascript html

我的代码如下所示:

xyz.html

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Status</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
</head>

<body>
  <div style="width: 300px;padding: 10px;margin: 0 auto;background: #f2f2f2;">
    <form name="Form">
      <input type="hidden" name="Status" value="<?php echo $_POST['Status'] ?>" />
    </form>

    <script type="text/javascript">
      alert(window.onload);
      window.onload = function() {
        var xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://api.com');
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function() {
          if (xhr.status === 200) {
            var apiresponse = JSON.parse(xhr.response);
            console.log(apiresponse);
            if (apiresponse.status == "200") {
              document.getElementById('response').innerHTML = apiresponse.message + '<br/> Press back button to continue in App.';
            } else {
              document.getElementById('response').innerHTML = JSON.stringify(apiresponse);
            }
          } else {
            document.getElementById('response').innerHTML = JSON.stringify(xhr);
          }
        };
        var elements = document.forms['Form'].elements;
        let formBody = [];
        for (var i = 0, element; element = elements[i++];) {
          let encodedKey = encodeURIComponent(element.name);
          let encodedValue = encodeURIComponent(element.value);
          formBody.push(encodedKey + "=" + encodedValue);
        }
        formBody = formBody.join("&");
        document.getElementById('request').innerHTML = formBody;
        xhr.send(formBody);
      }
    </script>
</body>

</html>

当我运行上面的代码时,在alert方法中,我得到了null的值,而在window.onload = function()中给出的下面的函数根本没有被调用。因此,有什么需要包含的内容来完成它。

1 个答案:

答案 0 :(得分:2)

调用alert(window.onload)时为空,因为尚未为window.onload分配功能。您的alert不能证明任何事情。

要进行健全性检查,请在绑定到alert('hello world');的{​​{1}}中的行var xhr = new XMLHttpRequest();上方添加代码function。您可能会发现正在调用您的函数,但其​​行为未达到您的预期,因此您认为不是在window.onload上调用了函数,但实际上是在调用。

相关问题