首页 > 解决方案 > 使用ajax从javascript调用php函数的问题

问题描述

我正在尝试建立一个评级系统,需要从文件 startating.php 调用一个函数并在那里传递变量 - $id(post id)和评级百分比。我不知道如何调用这些变量,然后在 startating.php 中引用它们这是我的代码:

$( function() {
    var postID = <?php echo $id; ?>;

    var rating = new starRating( { // create first star rating system on page load
        containerId: '$id', // element id in the dom for this star rating system to use
        starWidth: 60, // width of stars
        starHeight: 60, // height of stars
        ratingPercent: '0%', // percentage star system should start 
        canRate: true, // can the user rate this star system?

        user: '$userLoggedIn',

        onRate: function() { // this function runs when a star is clicked on
            //console.log( rating );
            $.ajax({
                url: '../handlers/starating.php', 
                type: 'POST', 
                data: 'post_id='+postID+'&rating_num='ratingPercent,
                dataType: 'json',
                success: function(){
                    console.log('works');
                }
            }); 
            //alert('You rated ' + rating.newRating + ' starts' );
        }
    } );
} );

标签: javascriptphpajax

解决方案


Welcome to the community.

First of all, it is not a good idea to include php code directly in the js file, for many reasons among them, readability, security etc. These two should be strictly separated and have the ajax to control what happens between.

Here is an example:

JS

function Call_AJAX({do_action,ajax_id,do_success}) {
        $.ajax({
            type : 'POST',
            url : ajax_url,
            dataType : 'json',
            data : {
                action : do_action,
                id: ajax_id
            },          
            success : do_success
        });
    };

php

function call_php_function(){           
    $id   = $_POST['id'];       

    //Do something wit the call then return result
    $result = do_something();           
    echo json_encode($result);  
    exit;           
};

then you can call this like this in js:

//Get some sort of result
var result_append = function (data) {
    //Do something with the returned data
    console.log(data.result)
};  

Call_AJAX(
    do_action = 'call_php_function',
    ajax_id = some_ajax_id,
    do_success = result_append);    

This way, you can call a specific function in php (such as call_php_function()), then get the rating information. Once you got the result, then send it back via json_encode. And you can display them once ajax call is a success. You can implement error handling in both sides. This way that whatever happens in front-end doesn't affect the back-end, visa versa.

Hope this helps.


推荐阅读