簡體   English   中英

我想從jquery ajax調用Php用戶定義函數

[英]i want to Call Php user define function from jquery ajax

我想從jquery ajax( $.ajax({}) )調用php用戶定義函數

我的ajax代碼在index.php中,php用戶定義函數在functions.php中

兩者都在同一個文件夾中

這是我的index.php代碼

<html>
<head>
<script src="headerfiles/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function()
{
        $("#display").click(function()
        {
                var mobile=$("#mobile").val();
                $.ajax({
                method:"post",
                url:"functions.php",
                success:function(name){alert(name);}
                });
        });
});

</script>

</head>
</body>
<input type="text" id="mobile" name="mobile" />
<input type="button" id="display" name="display" value="Display" />
</body>
</html>

和functions.php代碼是

function fetch_name($mobile)
{      
    $name="my query............"
    echo $name;
    //or
    return $name;
}

我想在index.php頁面中顯示名稱

你可以這樣做

在js中添加:

data:{fc : 'fetch_name'};

在PHP中

$fc = $_POST['fc'];
$fc();

function fetch_name($mobile)
{      
  $name="my query............"
  echo $name;
  //or
  return $name;
}

根據你的腳本Html: -

<html>
<head>
<script src="headerfiles/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function() {

    $("#display").click(function(e)
    {
        var postData = $('#mobile').val(); // Data which you may pass.
        var formURL = 'function.php'; // Write callback script url here
        $.ajax(
        {
        url : formURL,
        type: "POST",
        data : postData,
        success:function(data, textStatus, jqXHR)
        {
            alert(data);
            //data: return data from server
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            //if fails     
        }
        });
    });
});
</script>

</head>
</body>
<input type="text" id="mobile" name="mobile" />
<input type="button" id="display" name="display" value="Display" />
</body>
</html>

在function.php中: -

<?php
    // Post Value
    $mobile = isset($_POST['mobile']) ? $_POST['mobile'] : '';

    fetch_name($mobile);

    function fetch_name($mobile) {
      echo $mobile;
     // Your function body goes here.
       exit;
    }

?>
//In your ajax send a post param 


$.ajax({
method:"post",
url:"functions.php",
data: { 
        'foo': 'function_name', 
    },
............
.................

In your functions.php

//capture the post param foo to get the function name 
//set it to null if its not sent
$foo  = isset($_POST['foo']) ? $_POST['foo'] : null;

//if foo is set call the function
if($foo){
$foo();
}

PS我不知道你為什么要調用functions.php中的函數,而你可以從index.php和include.php中調用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM