简体   繁体   English

使用AJAX从JavaScript调用PHP函数

[英]Calling a PHP function from JavaScript using AJAX

I'm trying to call a PHP function using AJAX. 我正在尝试使用AJAX调用PHP函数。 I've checked stack overflow for solutions (which it showed in masses) but it still doesn't seem to work for me. 我已经检查了堆栈溢出的解决方案(它已批量显示),但它似乎仍然对我不起作用。 Note that the PHP code and JavaScript / jQuery / AJAX code are all in the same file. 请注意,PHP代码和JavaScript / jQuery / AJAX代码都在同一文件中。

Below is the code I wrote to try and get the desired results, the two PHP files included have nothing to do with any of the PHP functions I need to call so I did not post those. 下面是我为尝试获得期望的结果而编写的代码,其中包含的两个PHP文件与我需要调用的任何PHP函数均无关,因此没有发布它们。

(Note: The ExecuteAll() function gets called, but nothing happens after/in the AJAX code) (注意:ExecuteAll()函数被调用,但是在AJAX代码之后/之中没有任何反应)

<input type="button" value="Show all client data" id="all">

<?
include('inc/php/stringgenerator.php');
include('inc/php/client.php');

$generator = new StringGenerator;

$clients = array();

for($i = 0; $i < 250; $i++){
    $clients[$i] = new Client;
    $clients[$i]->SetId($i);
    $clients[$i]->SetAddress($generator->GetGeneratedString(rand(12, 24)));
    $clients[$i]->SetNotes("Notes for client " . $i);

    $scores = array();
    for($j = 0; $j < 25; $j++)$scores[$j] = rand(0, 10);
    $clients[$i]->SetScores($scores);
}    

echo "Clients generated";
?>
<?
switch($_POST["functionname"]){
    case 'DisplayAllClientData':
        DisplayAllClientData();
        break;
};

function DisplayAllClientData(){
    for($i = 0; $i < count($clients); $i++){
        $clients[$i]->PrintClientData();
        echo "<hr>";
    }
}  
?>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript" language="javascript">
$(document).ready(function(){
    $("#all").click(function(){ ExecuteAll(); });
}); 

function ExecuteAll(){
    $.ajax({
        type: "POST",
        url: 'index.php',
        data: {functionname: 'DisplayAllClientData'},
        succes:function(){
            alert("Success!");
        }
    });
}
</script>

Try this: 尝试这个:

In JS: 在JS中:

function ExecuteAll(){
    $.ajax({
        type: "POST",
        url: 'index.php',
        data: {command: 'all_client_data'},
        succes:function(){
            alert("Success!");
        }
    });
}

Then in your PHP do the following after declaring the DisplayAllClientData() function: 然后,在PHP中,声明DisplayAllClientData()函数后执行以下操作:

if ($_POST['command'] == 'all_client_data') [
    DisplayAllClientData();
}

Something along those lines should work. 遵循这些原则的东西应该起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM