Firefox的Javascript问题:表单提交时不更新状态

Firefox issue with Javascript: Not updating status on form submission

本文关键字:更新 状态 表单提交 Javascript 问题 Firefox      更新时间:2023-09-26

现在我已经多次尝试通过Ajax将表单数据发送到服务器脚本而不刷新页面(使用表单的onSubmit事件)。所有的浏览器(Chrome, IE等)都可以正常工作,但当涉及到Firefox时,处理还在继续。我的意思是,即使数据已经发送到服务器端(是的,在很多时候,我已经在服务器端获得了数据,但客户端仍在处理中),客户端也不会响应连续的调用。

例如,考虑我的一个示例代码:

这是Javascript

function submitComment(id)
{
 //id is the id of the postbox
 var content=$("#"+id).val();
 var xmlhttp;
 if(window.XMLHttpRequest)
  xmlhttp=new XMLHttpRequest();
 else
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
 xmlhttp.onreadystatechange=function()
 {
  if(xmlhttp.readyState==4 && xmlhttp.status==200)
  {
   //action taken in response to the script from server in response to this form submission, eg, enabling back the submit button
   $('input[type="submit"]').removeAttr('disabled');
  }
 }
 $('input[type="submit"]').attr('disabled','disabled');
 xmlhttp.open("POST",host+"comment.php?mode=newpost",true);
 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
 xmlhttp.send("post="+content);
 $('#status').html('Posting your comment. Please wait...');//shows this status as long as gets no response from server
 return false;
}

这里是它的HTML:

<form id='newpostform' method=post action='' onSubmit="return submitComment('post')" >
 <textarea id='post' name='post'></textarea>
 <input type=submit value=Post>
 <span id='status' style='padding:10px; font-size:12px; color:black; font-family:cambria, segoe ui;'>
 </span>
</form>

所以,在所有浏览器中,除了Firefox,提交按钮被禁用了一段时间,直到脚本将帖子发送给服务器,当服务器响应时,提交按钮被激活并更新状态。

问题出现在Firefox中。状态栏永远不会改变它的状态,即使数据已经传达给服务器!

评论中的答案:

我的问题解决了。XMLHTTPRequest。在firefox3.5中,status返回0,responseText为空白

这只是因为我使用了绝对路径。使用相对路径解决了我的问题。

太棒了!


关于你附加的问题:

然而,我仍然感到困惑的事实是,我必须使用这样的相对路径:index/index.php在脚本文件的路径属性驻留在索引目录本身。为什么?我的意思是,简单地使用'index.php'应该已经解决了问题,不是吗?

正如我所理解的,你有你的HTML在http://example.org/test.html与

<script src="subdir/main.js>

…它解析为http://example.org/subdir/main.js,它调用XMLHttpRequest:

xhr.open("POST", "index.php", true);

请求http://example.org/index.php,而不是http://example.org/subdir/index.php

这是因为XMLHttpRequest中的相对URL(与许多其他情况一样)是根据文档的基本URL而不是脚本的URL进行解析的。

如果相对URL是针对脚本的URL解决,它可能会变得非常混乱:想象一下你有jQuery在/lib/jquery.js,它调用XMLHttpRequest和你自己的代码在/main.js调用jQuery.ajax(…"data.txt"…)。该请求/data.txt还是lib/data.txt ?