是否可以在ajax调用中传递变量?

时间:2014-07-17 08:52:39

标签: javascript php 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中,我有这个功能。我想在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'];
        }
    }
} 

3 个答案:

答案 0 :(得分: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);
                    }
                });
           });

答案 1 :(得分: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/

答案 2 :(得分: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']都将包含您的数据。