2013-03-11 34 views
1

只要用戶點擊一個按鈕,我一直在撞牆,試圖將遊戲名稱傳遞給我的PHP函數。這個想法是用戶點擊一個按鈕,該按鈕具有其視頻遊戲名稱的值,然後php腳本檢查該遊戲的排名並將該排名返回給html。我之前提出了發佈請求,甚至在這裏我手動將變量名稱設置爲其中一個遊戲來測試它時,它就可以工作。請幫忙!如何讓我的jquery post請求在點擊時使用從函數中存儲的變量?

<script> 
$(document).ready(function(){ 
    //global n variable 
    n = $(); 

     $('#target').click(function(){ 
      //set value of n to the game's name 
       n = $(this).val(); 

     }); 

     //then send the name as term to my php function to deal with it and return 
     //the ranking 
    $.post('getTotal.php', {term: n}, function(data){ 
     //been trying to see if anything comes through for debugging purposes 
       alert(data); 

     //commented this out for now, just puts it in the div I left open 
     //$('#total').html(data); 
    }); 

}); 

</script> 

回答

0

只是當用戶點擊按鈕。點擊處理程序中,獲得的價值和執行HTTP POST

$ AJAX或$ POST

如 -

$(document).ready(function() { 
     $('#target').click(function() 
      $.ajax({ 
       type: "POST", 
       url: "url...", 
       data: "n="+nVal+", 
       success: function(html){ 
       alert("Submitted"); 
       } 
      }); 
     }); 
}); 
1

你應該把$.post到您單擊處理......所以,當你實際點擊按鈕...現在你的代碼設置了一個n變量它將只運行,它的值是一個空的jQuery對象(爲什麼?)。然後它在按鈕上附加一個點擊處理程序。然後它運行一個$.post請求 - n仍然是一個空的jQuery對象。點擊按鈕發生得多......

另外,應該避免使用全局變量。在聲明變量時應該使用var關鍵字。

相關問題