如何仅在未处理表单时运行某个 Javascript 片段?
我有一段 Javascript,我想在表单加载时运行。表单自行处理。当表单加载时,Javascript 工作得很好,但是当提交表单并且页面自行处理时,Javascript 会破坏它。
有没有办法让 Javascript 仅在表单未处理时运行?
更新:
处理表单时出现此错误(Javascript 正在执行 AJAX 请求):
类型错误:“未定义”不是对象 XMLHttpRequest 无法加载 [ajax 请求 url] Origin [原始页面] 不允许 Access-Control-Allow-Origin
这是 HTML:
<form method="#" action="post">
<!--form elements-->
</form>
这是 Javascript:
ajax.onreadystatechange=function() {
if (ajax.readyState==4 && ajax.status==200) {
document.getElementById("invitestar-message").innerHTML=ajax.responseText;
var signup = document.getElementById("invitestar-content-container");
setTimeout(function(){
body.removeChild(document.getElementById('invitestar-verifying'));
signup.style.display = "block";
}, 500);
}
}
ajax.open("GET","http://nvrforget.com/invitestar/check-invite/?invite=kNdqyJTjcf",true);
ajax.send();
运行此 javascript 的域不是 http:// /nvrforget.com/
。
I have a piece of Javascript I want to run when a form loads. The form handles itself. When the form loads the Javascript works great, but when the form is submitted and the page handles itself the Javascript breaks it.
Is there a way to make the Javascript only run when the form is not being handled?
UPDATE:
I get this error when the form is handled (the Javascript is doing a AJAX request):
TypeError: 'undefined' is not an object
XMLHttpRequest cannot load [ajax request url] Origin [original page] is not allowed by Access-Control-Allow-Origin
Here is the HTML:
<form method="#" action="post">
<!--form elements-->
</form>
Here is the Javascript:
ajax.onreadystatechange=function() {
if (ajax.readyState==4 && ajax.status==200) {
document.getElementById("invitestar-message").innerHTML=ajax.responseText;
var signup = document.getElementById("invitestar-content-container");
setTimeout(function(){
body.removeChild(document.getElementById('invitestar-verifying'));
signup.style.display = "block";
}, 500);
}
}
ajax.open("GET","http://nvrforget.com/invitestar/check-invite/?invite=kNdqyJTjcf",true);
ajax.send();
The domain that this javascript is run on is not http://nvrforget.com/
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此错误:
是因为您无法对网页所在的不同域进行 ajax 调用而引起的。请参阅同源策略的说明。
JSONP 是一种进行跨域 ajax 调用的方法。它需要一个协作服务器(以实现 JSONP 的服务器端)以及将 ajax 请求添加为脚本标记的方法。像 jQuery 或 YUI 这样的库支持 JSONP 的客户端部分,或者您可以自己完成(但您仍然需要一个协作服务器)。如果您想了解更多信息,请谷歌 JSONP。
This error:
is caused because you can't make ajax calls to a different domain than the web page is located on. See this description of the same-origin policy.
JSONP is a way to make cross-origin ajax calls. It requires a cooperating server (to implement the server side of the JSONP) and a method of adding the ajax request as a script tag. Libraries like jQuery or YUI support the client-side parts of JSONP or you can do it yourself (but you still need a cooperating server). Google JSONP if you want to know more about it.