2015-04-20 63 views
1

我做了一个测试jQuery ajax脚本,并在提交时将其附加到表单中,但尽管我的函数结尾处有return false页面在提交时保持刷新,我也没有得到任何回应。jQuery ajax不起作用

的形式是这样的:

<form id="LogInForm" onsubmit="return LogIn();"> 
    <input type="text" placeholder="Username" name="Username"><br/> 
    <input type="password" placeholder="Password" name="Password"><br/> 
    <input id="LogIn" type="submit" value="Sign In"> 
</form> 

的脚本是这样的:

function LogIn() { 

    $.ajax({ 
      type:'POST', 
      url: 'login.php', 
      data:$('#LogInForm').serialize(), 
      success: function(response) { 
        alert(response); 
       }}); 
     return false; 
     } 

login.php文件只包含echo "test";

index.phplogin.php在同一个文件夹中。

回答

3

我刚刚从你的表格中删除了onsubmit并将其实施到脚本中。

<form id="LogInForm"> 
    <input type="text" placeholder="Username" name="Username"><br/> 
    <input type="password" placeholder="Password" name="Password"><br/> 
    <input id="LogIn" type="submit" value="Sign In"> 
</form> 

脚本

$(function() { 
    $("#LogInForm").submit(function() { 
     $.ajax({ 
      type:'POST', 
      url: 'login.php', 
      data:$('#LogInForm').serialize(), 
      success: function(response) { 
       alert(response); 
      }}); 
     return false; 
    }); 
}); 
+0

非常感谢!这有点奇怪,因为我的代码与我在另一个项目中发布的代码几乎相同(使用'onsubmit =“return function();”'thing),并且它工作正常。更具体地说,这一个:http://stackoverflow.com/questions/29460437/return-false-doesnt-work-for-jquery-post-form-submission-when-script-is-loade – Colin

0
$(function() { 
    $("#LogInForm").submit(function() { 
     $.post('login.php', $("#LogInForm").serialize()).done(function(data) { 
      alert(data); 
     }); 
    }); 
}); 

和HTML

<form id="LogInForm"> 
    <input type="text" placeholder="Username" name="Username"><br/> 
    <input type="password" placeholder="Password" name="Password"><br/> 
    <input id="LogIn" type="submit" value="Sign In"> 
</form>