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 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥15 关于logstash转发日志时发生的部分内容丢失问题
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题