2014-01-29 38 views
10

當用戶點擊一個提交按鈕時,我必須構建一個ajax調用,所以我包含了jquery,並且我寫了下面的代碼(取自jquery文檔):Jquery ajax調用點擊事件提交按鈕

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
<script> 
$(document).ready(function(){ 
    $("Shareitem").click(function(e){ 
     e.preventDefault(); 
    $.ajax({type: "POST", 
      url: "/imball-reagens/public/shareitem", 
      data: { id: $("Shareitem").val(), access_token: $("access_token").val() }, 
      success:function(result){ 
     $("sharelink").html(result); 
    }}); 
    }); 
}); 
</script> 

HTML:

<div id="sharelink"></div> 
[...] 
<input type="hidden" name="id" value="" id="id"></dd> 
<dd id="access_token-element"> 
<input type="hidden" name="access_token" value="xxxxxxxx" id="access_token"></dd> 
<dt id="Shareitem-label">&#160;</dt><dd id="Shareitem-element"> 
<input type="submit" name="Shareitem" id="Shareitem" value="UpdatedByPreviousAjaxCall"></dd></dl></form> 

的問題是,在執行提交操作,但Ajax調用不在以下,這樣的形式執行請求的提交操作,而不是停留在同一個頁面和更新所需「div」的內容。

我錯過了什麼?我錯在哪裏? 在此先感謝您的任何提示。

+1

'$( 'Shareitem')'和'$( 'sharelink')'是不是好選擇.... –

回答

14

您沒有在按鈕的id之前添加#。你的jQuery代碼中沒有正確的選擇器。所以jquery永遠不會執行你的按鈕點擊。它直接提交你的表單而不通過任何Ajax請求。

查看文檔:http://api.jquery.com/category/selectors/
它的你的朋友。如果你想傳遞的

<input type="hidden" name="id" value="" id="id"> 

你需要改變這一行的值

似乎id: $("#Shareitem").val()是錯誤的:通過

id: $("#Shareitem").val() 

試試這個

id: $("#id").val() 

一起:

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> 
    <script> 
    $(document).ready(function(){ 
     $("#Shareitem").click(function(e){ 
      e.preventDefault(); 
     $.ajax({type: "POST", 
       url: "/imball-reagens/public/shareitem", 
       data: { id: $("#Shareitem").val(), access_token: $("#access_token").val() }, 
       success:function(result){ 
      $("#sharelink").html(result); 
     }}); 
     }); 
    }); 
    </script> 
+0

你的答案是工作和精確的(我並沒有引起它晚了,所以我的思維有點混亂,但無論如何,我不得不改變jquery包含的方式,因爲我使用SSL我遵循[本教程](http://stackoverflow.com/questions)/18251128 /爲什麼-AM-I-突然-得到-A-阻止加載混合活性化內容的問題,在火) – softwareplay