dongqiao9583 2014-06-13 18:44
浏览 53

使用AJAX从JavaScript调用PHP函数

I'm trying to call a PHP function using AJAX. 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.

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.

(Note: The ExecuteAll() function gets called, but nothing happens after/in the AJAX code)

<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>
  • 写回答

1条回答

  • douhan9191 2014-06-13 18:55
    关注

    Try this:

    In 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:

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

    Something along those lines should work.

    评论

报告相同问题?

悬赏问题

  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架