2014-07-17 67 views
-3

是否有可能在ajax調用中傳遞變量?是否可以在ajax調用中傳遞變量?

$(document).on('click','#Quote_create_value',function(){ 
      $template = $(this).val(); 
       $.ajax({ 
        type : 'GET', 
        url : '../../../protected/config/ajax.php',  
        data:"function=result($template)", 
        success : function(response){ 
         $("#Quote_template_value").html(response); 
        } 
       }); 
      }); 

在ajax.php,我有fuction.I想調用結果函數在ajax.php 我沒有得到生存。

if(isset($_GET['function'])) { 
    if($_GET['function'] == 'templateDropDown') { 
     $query = "select * from quote where template IS NOT NULL"; 
     $result = mysql_query($query, $con); 
     while ($row = mysql_fetch_assoc($result)) { 
      echo '<option value="'.$row['template'].'">' . $row['template'] . '</option>'; 
     } 
     mysql_free_result($result); 
    } 
    elseif($_GET['function'] == 'result($template)') { 
     $query = "select * from template where templateName=$template"; 
     $result = mysql_query($query,$con); 
     while ($row = mysql_fetch_assoc($result)) { 
      echo $row['unitcost']; 
     } 
    } 
} 
+0

請參閱http://stackoverflow.com/questions/18413969/pass-variable-to-function-in-jquery-ajax-success-callback –

+0

我假設您想要$ template爲var'template'? – t3chguy

+0

現在這個問題還不是很清楚。結果是一個PHP函數嗎? –

回答

2
$(document).on('click','#Quote_create_value',function(){ 
      $template = $(this).val(); 
      var functionVal = result($template) 
       $.ajax({ 
        type : 'GET', 
        url : '../../../protected/config/ajax.php', 
        data:"function=result("+functionVal+")", 
        success : function(response){ 
         $("#Quote_template_value").html(response); 
        } 
       }); 
      }); 
+0

我沒有得到迴應。我認爲有一些錯誤。 – user9293

0

是...你可以這樣做:

$.ajax({ 
    type: "POST", 
    url: "some.php", 
    data: { name: "John", location: "Boston" } 
}).done(function(msg) { 
     alert("Data Saved: " + msg); 

});

請檢查的jQuery的文檔Ajax請求:http://api.jquery.com/jquery.ajax/

0

如果你只是想傳遞的$template的值稱爲result一個PHP函數中使用,你可以這樣做:

// no advantage to using 
// $(document).on('click','#Quote_create_value' 
$('#Quote_create_value').on('click', function() { 
    var $template = $(this).val(); // no longer a global variable   
    $.get({       // shorthand for AJAX GET request 
     url : '../../../protected/config/ajax.php',  
     data : { function : result($template) }, 
     success : function(response) { 
      $("#Quote_template_value").html(response); 
     } 
    }); 
}); 

這將JS函數result($template)的結果傳遞給url。對於GET請求,jQuery將序列化data屬性並形成一個查詢字符串,該字符串將附加到該URL。如果你願意,你可以只是做自己通過改變url屬性

url : '../../../protected/config/ajax.php&function=' + result($template) 

,而不是指定data屬性。

無論哪種方式,服務器上的$_GET['function']都會包含您的數據。

相關問題