2013-01-15 113 views
1

任何人都可以帮我理解为什么代码不起作用吗?为什么我的简单ajax代码不起作用?

它不会将div中的文本更改为成员编写的文本。

而且事先说一句抱歉,我的英语,我的英语老师显然我以前不做好... =/

第一页:

<script> 
function showUser() 
{ 
var str = document.forms["myForm"]["users"].value; 
if (str=="") 
    { 
    document.getElementById("txtHint").innerHTML=""; 
    return; 
    } 
if (window.XMLHttpRequest) 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    { 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
xmlhttp.onreadystatechange=function() 
    { 
    if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText; 
    } 
    } 
xmlhttp.open("GET","act2.php?q="+str,true); 
xmlhttp.send(); 
} 
</script> 

<form name="myForm" onsubmit="return showUser()" method="post"> 
First name: <input type="text" name="users"> 
<input type="submit" value="Submit"> 
</form> 

<div id="txtHint"><b>Person info will be listed here.</b></div> 

第二页(act2.php ):(校正名称)

<?php 
$q=$_GET["q"]; 

echo "$q"; 
?> 
+3

什么问题呢? –

+0

它显示任何错误? –

+0

不知道为什么人们使用普通的JavaScript,而不是jQuery的,举例来说。跨浏览器解决方案,并且很容易。post(url,{key:value},function(response){alert(response);});' – devdRew

回答

0

你的函数需要返回false,防止表单的默认操作,否则你的表格将被提交(这默认操作)。

只需在代码末尾添加一个return false即可。

function showUser(){ 

    // ... 
    xmlhttp.send(); 

    // prevents the default action (the submit from your form) 
    return false; 

} 

或:

<form name="myForm" onsubmit="showUser();return false;" method="post"> 

您也可以安全地删除IE5/6 compat的代码。

if (window.XMLHttpRequest) 
    xmlhttp=new XMLHttpRequest(); 
    } 
else 
    { 
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

简直变成:

var xmlhttp=new XMLHttpRequest(); 

在前面的var是非常重要的,否则xmlhttp将成为全球对象,而不是一个范围变量的成员。

+0

谢谢!你非常帮助我! – ldoroni

+0

不客气;) – Christoph

1

在此行中指定的文件

xmlhttp.open("GET","act2.php?q="+str,true); 

act2.php,但根据您的文章,您正在寻找ajax2.php,会是它?

+0

+1我也被弄糊涂了。 –

+0

不,这不是问题,我错了,只是在这篇文章中写了文件的名称。该文件的真实姓名是act2.php – ldoroni

1

你只是忘记了在showUser方法“返回false”的形式将发布如常在Ajax调用由

编辑前: 为了澄清,在你返回showUser的的onsubmit( ),showUser方法永远不会返回值,以阻止浏览器发布表单。另外,正如其他海报所建议的那样,你暗示php文件被命名为ajax2.php,但代码实际上试图命中act2.php。

而且,使用某种框架(jQuery是非常流行)的建议。

+0

我很抱歉,但我的英语不好,我似乎无法理解你写给我的关于retun false的内容。你可以告诉我你的代码是什么?我认为这会帮助我更好地理解你。我正在使用ajax而不是jquary,因为我试图学习 – ldoroni

+0

为什么我应该加载一个80k框架来做简单的ajax调用? – Christoph

0

只是为了向您展示如何以较少的痛苦和jQuery来做同样的事情。

<form name="myForm" action="/act2.php"> 
    <input type="text" name="q"> 
    <input type="submit"> 
</form> 

<div id="txtHint"></div> 

<script type="text/javascript"> 
    $(document) 
     // Link handler for submiting form 
     .on('submit', 'form[name="myForm"]', function(e) { 
      // Preventing original form submition 
      e.preventDefault(); 

      // Send all data from form, to url from form's action attribute (/act2.php) and set received data to div with id txtHint 
      $.get($(this).attr('action'), $(this).serialize(), function(data, status, xhr) { 
       $('#txtHint').html(data); 
      }); 
     }); 
</script>