doufuxing8562
doufuxing8562
2014-12-03 06:28
浏览 38

AJAX函数在PHP文件中访问PHP函数

I have a working AJAX file that will execute the content in a PHP file. However, if the php is within the function(there are alot of php funtion in a PHP file), how do I call only the function that I want.

My AJAX code:

$(document).ready(function(){

// use ajax, call the PHP
$.ajax({
    url: 'postme.php', 
    success: function(response){
        $('.result_Postme').text(response);
    }
})
});

one of the function in postme.php PHP file:

<?php 
  function echo()
  {
    echo 'Text';
  }
?>

Thanks.

EDIT:

@Amadan hi, i tried ur method but it doesn't seems to be outputting in the html.

My AjAx code:

$(document).ready(function(){

// use ajax, call the PHP
$.ajax({
    url: 'rank.php', 
    data: {
        action: 'echo'
    },
    success: function(response){
        $('.rank_Alibaba').text(response);
    }
})
});

PHP file

switch($_REQUEST['action']) 
{
 case 'echo': 
 echo "text";
 break;
 }

HTML:

 <td class="rank_Alibaba"></td>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

6条回答 默认 最新

  • douliao2493
    douliao2493 2014-12-03 06:31
    已采纳

    a) Use a MVC framework, such as Laravel or CakePHP. Such frameworks are quite opinionated and will force best practices on you, whether you want them or not. :P

    b) If you absolutely want to stick with plain PHP, the easiest way is to pass a parameter to select your function, and then in your PHP file have a switch statement on that parameter that will dispatch the call to the correct place. For example, in JavaScript:

    ...
    url: 'postme.php', 
    data: {
      action: 'echo'
    },
    ...
    

    In PHP:

    switch($_REQUEST['action']) {
      case 'echo':
        echo();
        break;
      ...
    }
    
    点赞 评论
  • drrhr20884
    drrhr20884 2014-12-03 06:30

    You need to call the function in your PHP file:

    Append a line in the end.

       <?php 
        function yourFunc() {
          echo 'Text';
        }
        yourFunc()
        ?>
    

    How come PHP parser know that you need to execute the code from the function.

    点赞 评论
  • doupeng5320
    doupeng5320 2014-12-03 06:34

    You cannot directly call a php function through javascript. What you can do is something like a "dispatcher".

    $(document).ready(function(){
    
        // use ajax, call the PHP
        $.ajax({
            url: 'postme.php', 
            data: { func: "echo" }
            success: function(response){
                $('.result_Postme').text(response);
            }
        })
    });
    

    and in php:

    <?php 
      if($_REQUEST["func"] == "echo") {
        echo();
      } elseif(....) {
    
      }
    
      function echo()
      {
        echo 'Text';
      }
    ?>
    
    点赞 评论
  • doushi4633
    doushi4633 2014-12-03 06:34

    You have to control the php behaviour according to the input query.

    Add this to your php script and may be work(just a sample):

    <?php 
      if(isset($_GET['action']) && $_GET['action']) == 'echo'){
        echo();
      }else{
        // original behaviour
      }
      function echo()
      {
        echo 'Text';
      }
      // whatever function else
    ?>
    

    And change your javascript to:

    $(document).ready(function(){
    
    // use ajax, call the PHP
    $.ajax({
        url: 'postme.php?action=echo', 
        success: function(response){
            $('.result_Postme').text(response);
        }
    })
    });
    
    点赞 评论
  • dtmu88600
    dtmu88600 2014-12-03 06:35

    You can even make use of the $_GET var like this.

    $.ajax({
        url: './inc/postme.php?argument=myFunction',
        type: 'POST',
        data: selected
        success: function(response){
            $('.result_Postme').text(response);
        }
    });
    

    and on the php side:

    if($_GET['argument'] == 'myFunction'){
        //code here
    }
    
    点赞 评论
  • douzhang1115
    douzhang1115 2014-12-03 07:04

    I have 3 files: 1-Javascript 2-ADMIN.php 3-Class.php (where I store my functions)

    In java script I use AJAX and JSON and allways send a objectEvent (ObjEvn) to ADMIN.php:

        //Your javaScript code
        $(document).on("event", "#idElement", function(){
            //Data you want to send to php evaluate
             var dt={ 
                      ObjEvn:"btn_Login",//This is the controller to ADMIN.php
                      dataJsToPHP: $("#txt_EmailLogin").val(),
                      asManyasYouWant: use jQuery to grab values....
                    };
    
            //Ajax      
             var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
                                    url: "ADMIN.php",
                                    type: "POST",
                                    data: dt,
                                    dataType: "json"  
                                });
    
            //Ajax Done catch JSON from PHP 
                request.done(function(dataset){
                    for (var index in dataset){ 
                         dataPHPtoJsJS=dataset[index].dataPHPtoJs;
                         asManyasYouWantJS=dataset[index].asYouWant;
                     }
    
                     //JavaScript conditions. Here you can control the behaivior of your //html object, based on your PHP response
                     if(dataPHPtoJsJS){
                        $( "#idYourHtmlElement" ).removeClass( "class1" )
                        $( "#idYourHtmlElement" ).addClass( "class2" )
                     }
    
    
             }); 
    
            //Ajax Fail 
                request.fail(function(jqXHR, textStatus) {
                    alert("Request failed: " + textStatus);
                }); 
        }
    

    Now in ADMIN.php

    $ObjEvn=$_POST["ObjEvn"];//Call this before all test
    $asManyasYouWant = $_POST["asManyasYouWant "];
    
    if($ObjEvn==="btn_Login"){
    $login=$_POST["login"];
    $passwd=$_POST["passwd"];
    //call your function to test login in class.php
    //finally, at the end, return your result to jquery. It could be another jquery code to //be loaded dynamiclly, it could be a html tag, it could be a value... it could be almost //everyting..
    $arrToJSON = array(
            "dataPHPtoJs"=>"yourData",
            "asYouWant"=>"<div class=\".class1\">soemting</div>"    
            );  
            return json_encode(array($arrToJSON));
    }
    elseif($ObjEvn==="btn_NewUser"){
    //retrieve anoter values
    //and call your functions to create new user
    //finally, at the end, return your result to jquery. It could be another jquery code to //be loaded dynamiclly, it could be a html tag, it could be a value... it could be almost //everyting..
    $arrToJSON = array(
            "dataPHPtoJs"=>"yourData",
            "asYouWant"=>"<div class=\".class1\">soemting</div>"    
            );  
            return json_encode(array($arrToJSON));
    }
    
    点赞 评论

相关推荐