2013-02-11 121 views
0

我想使用Javascript/AJAX將所選單選按鈕的值變爲一個PHP會話變量。除了頁面刷新之外,一切都可以使用。有沒有辦法不刷新頁面?如何不用HTML JQuery AJAX PHP刷新頁面?

的HTML:

<input type="radio" name="shipping_method" value="Standard"> Standard<br> 
<input type="radio" name="shipping_method" value="2-day"> 2-Day Air&#42<br> 
<input type="radio" name="shipping_method" value="Overnight"> Overnight<br> 

的JavaScript/AJAX(有一些警示註釋掉):

<script> 
$(document).ready(function() { 
    $("input[name=shipping_method]").on('change', function(){ 
     var shipping_method = $('input:radio[name=shipping_method]:checked').val(); 
/*       alert (shipping_method); */ 
    $.ajax ({ 
     type: "GET", 
     url: ajax/shipping_method.php?shipping_method="+shipping_method, 
      success : function(data){ 
/*      alert(data); */  
     }, 
        error : function(XMLHttpRequest, textStatus, errorThrown) { 
        alert("problem: " + errorThrown); 
      } 
    }); 
    }); 
}); 

的shipping_method.php:

<?php session_start(); ?> 
<?php 
     $shipping_method = $_GET['shipping_method']; 
     $_SESSION['shipping_method'] = $shipping_method; 
?> 
+0

是當您單擊單選按鈕時刷新頁面? – user20232359723568423357842364 2013-02-11 21:02:01

+0

給定代碼中的任何內容都不會導致頁面刷新。你遺漏了哪些部分?你可以用代碼 的客戶端部分創建一個JSFiddle嗎? – 2013-02-11 21:02:53

+0

請添加更多代碼,因爲確保此代碼不會刷新頁面 – Sedz 2013-02-11 21:26:22

回答

0

不知道爲什麼它是發生但嘗試阻止默認操作。將部分代碼更改爲:

$("input[name=shipping_method]").on('change', function(e){ 
e.preventDefault(); 
+0

爲什麼單選按鈕的選擇會導致頁面刷新?這不是「默認行動」 – 2013-02-11 21:04:01

+0

@PatBurke我不知道,但由於某種原因,似乎確實發生了 – 2013-02-11 21:04:48

0

using event.preventDefault();應該解決你的問題。