繁体   English   中英

在函数内部调用时ajax无法正常工作

[英]ajax doesn't work properly when call inside a function

我正在尝试调用一个具有ajax请求的javascript函数,但该函数不起作用,因为没有任何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> 

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

单击链接时会发生什么?

  1. 点击事件触发
  2. JavaScript处理所有事件
  3. 浏览器将加载href指定的页面(本例中为当前页面)。

因此,这里将发生两件事之一:

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

要么

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


如果您想让人们点击一些东西来触发JavaScript,则可以投入精力来构建一个不错的解决方案 (如果JS成功,则具有服务器端的后备功能,并使用preventDefault ), 或者采用快捷而肮脏的方法来使用按钮链接。

暂无
暂无

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

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