使用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个回答



试试这个:</ p>

在JS中:</ p>

   function ExecuteAll(){
$ .ajax({
type:“POST”,
url:'index.php',
data:{command:'all_client_data'},
succes:function (){
alert(“成功!”);
}
});
}
</ code> </ pre>

然后在PHP中声明后执行以下操作 DisplayAllClientData()函数:</ p>

  if($ _POST ['command'] =='all_client_data')[
DisplayAllClientData();
}
</ code > </ pre>

这些方面应该有效。</ p>
</ div>

展开原文

原文

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.

doujingke4981
doujingke4981 会这样做,还需要一个代表upvote tho :(
6 年多之前 回复
dongshi6844
dongshi6844 没问题。 投票不会受到影响; )
6 年多之前 回复
dongluo3962
dongluo3962 嘿,伙计,谢谢你的回复! 我会在早上第一件事尝试。
6 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问