在函数

时间:2017-01-13 10:01:45

标签: javascript ajax

我正在尝试调用一个javascript函数,我有ajax请求并且它不起作用,因为没有任何responseText但是如果我把代码放在函数之外就像魅力一样。有人可以解释它是如何工作的吗?。

//This is here work properly.
console.log("addPostmanUser");
var data = JSON.stringify({
  "email": "holahola@local.es",
  "password": "12345",
  "username": "holahola",
  "name": "holahola",
  "surname": "toledo",
  "birthDate": 687045600000,
  "enabled": true,
  "authorities": [],
  "groups": [],
  "character": null,
  "locale": null,
  "registrationToken": null,
  "facebookId": null,
  "pushToken": null,
  "termsDate": null
});
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function(e) {
  if (xhr.readyState === 4) {
    console.log("addPostmanUser response: ");
    console.log(xhr);
  }
});
xhr.open("POST", "http://IP/user", true);
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);

//this one doesn't work
function inSameFile() {
  console.log("addPostmanUser");
  var data = JSON.stringify({
    "email": "holahola@local.es",
    "password": "12345",
    "username": "holahola",
    "name": "holahola",
    "surname": "toledo",
    "birthDate": 687045600000,
    "enabled": true,
    "authorities": [],
    "groups": [],
    "character": null,
    "locale": null,
    "registrationToken": null,
    "facebookId": null,
    "pushToken": null,
    "termsDate": null
  });
  var xhr = new XMLHttpRequest();
  xhr.withCredentials = true;
  xhr.addEventListener("readystatechange", function(e) {
    if (xhr.readyState === 4) {
      console.log("addPostmanUser response: ");
      console.log(xhr);
    }
  });
  xhr.open("POST", "http://IP/user", true);
  xhr.setRequestHeader("accept", "application/json");
  xhr.setRequestHeader("content-type", "application/json");
  xhr.setRequestHeader("cache-control", "no-cache");
  xhr.send(data);
}
<link rel="stylesheet" href="https//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<form>
  <div>
    <a class="enter" href="" onClick="inSameFile();" id="btn_register">Registrarme</a>
    <br>
    <a class="enter" href="" id="btn_cancel">Cancelar</a>
    <br>
  </div>
  <div></div>
</form>

1 个答案:

答案 0 :(得分:0)

 <a class="enter" href="" onClick="inSameFile();" id="btn_register"   >Registrarme</a><br>

点击链接会发生什么?

  1. 点击事件触发
  2. JavaScript处理其上的任何事件
  3. 浏览器加载href中指定的页面(本例中为当前页面)。
  4. 因此,有两件事情会发生在这里:

    XHR请求发生得太慢,在这种情况下,它会在响应之前中止,因为托管它的页面将会消失。

    XHR对象将被记录到控制台,然后将加载新页面。这将破坏XHR对象(因为它存在于已经遗留的页面上),并且无法检查它的内容(尽管如果打开了日志保存,仍然会在控制台中显示摘要)。

    如果您想要点击某些内容来触发JavaScript,那么要么投入精力来构建decent solution(如果JS成功,则使用服务器端回退并使用preventDefault选择使用按钮而不是链接的快速和脏选项。