2015-04-20 105 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>