在PHP和JavaScript之间传递数据?

在PHP和JavaScript之间传递数据?,javascript,php,jquery,google-visualization,Javascript,Php,Jquery,Google Visualization,总体思路是在div中绘制某人分数的图形。我有一个按钮,单击该按钮可运行图形绘制功能。我还有另一个函数,它使用switch语句从数据库检索数据,因为该函数与其他按钮共享 我的数据检索功能: var getdata = function(button_id) { $.ajax({ type: "POST", url: "../scripts/getdata.php", dataType: "html", data: {id: b

总体思路是在div中绘制某人分数的图形。我有一个按钮,单击该按钮可运行图形绘制功能。我还有另一个函数,它使用switch语句从数据库检索数据,因为该函数与其他按钮共享

我的数据检索功能:

var getdata = function(button_id) {
    $.ajax({
        type: "POST",
        url: "../scripts/getdata.php",
        dataType: "html",
        data: {id: button_id},
        success: function(result){
            $("#profilebox").html(result);
        }
    });
};
function drawVisualization() {

    getdata("profile_scores");

    // Create and populate the data table.
    var data = google.visualization.arrayToDataTable([
        ['', 'Correct', 'Incorrect'],
        ['Scores',  /* correct value */, /* incorrect value */],
    ]);

    var options = {
            'title': 'Total Scores Overall',
            'width': 600,
            'height': 400,
            'hAxis': {title: ''},
            'backgroundColor': 'transparent'
    };
    // Create and draw the visualization.
    new google.visualization.ColumnChart(document.getElementById('profilebox')).
    draw(data, options);
};
运行getdata.php并将值返回到空div中

getdata.php:

<?php
session_start();
$switchcase = $_POST['id'];
$email = $_SESSION['user']['email'];
//connect to database here
$result=mysqli_query($con,"SELECT * FROM users WHERE email = '$email'");
switch ($switchcase) {
    case "profile_home":
        while($row = mysqli_fetch_array($result)) {
        echo $row['username'] . "'s Profile<br><br>";
        echo "Name: " . $row['firstname'] . ' ' . $row['lastname'] . "<br><br>";
        echo "Things I like:<br>";
        echo $row['like'] . "<br><br>";
        echo "Things I dislike:<br>";
        echo $row['dislike'] . "<br><br>";
        echo "Other Sports:<br>";
        echo $row['sports'];
    };
        break;
    case "profile_scores":
        while($row = mysqli_fetch_array($result)) {
        $row['correct'];
        $row['incorrect'];
    };
        break;
    case "profile_merits":
        //CODE GOES HERE;
        break;
    case "profile_help":
        //CODE GOES HERE;
        break;
    case "profile_edit":
        //CODE GOES HERE;
        break;
}
mysqli_close($con);
?>
值返回到原始页面,并使其显示在图形中,其中

/* correct value */

是的

图形绘制功能:

var getdata = function(button_id) {
    $.ajax({
        type: "POST",
        url: "../scripts/getdata.php",
        dataType: "html",
        data: {id: button_id},
        success: function(result){
            $("#profilebox").html(result);
        }
    });
};
function drawVisualization() {

    getdata("profile_scores");

    // Create and populate the data table.
    var data = google.visualization.arrayToDataTable([
        ['', 'Correct', 'Incorrect'],
        ['Scores',  /* correct value */, /* incorrect value */],
    ]);

    var options = {
            'title': 'Total Scores Overall',
            'width': 600,
            'height': 400,
            'hAxis': {title: ''},
            'backgroundColor': 'transparent'
    };
    // Create and draw the visualization.
    new google.visualization.ColumnChart(document.getElementById('profilebox')).
    draw(data, options);
};
当用户单击按钮调用getdata函数,然后根据从getdata.php接收到的值绘制图形时,将运行此函数


非常感谢您的帮助:)

您的PHP代码可以将返回的参数编码为(JSON编码的)关联数组。然后,您可以通过ajax响应中的键分别检索它们,并在JavaScript代码中传递它们。

我完全不确定您要的是什么,但下面是我的猜测

如果希望从页面上的数据库中获取案例2中的$result。然后,您可以使用JSON将PHP数组传递给Javascript,然后完成剩余的工作。假设这是switch语句的第2种情况

case "profile_scores":
{
    $row = $result->fetch_array(MYSQLI_NUM);
    echo json_encode($row);
    break;
}
在ajax响应中,您可以这样做

$.ajax({
    type: "POST",
    url: "../scripts/getdata.php",
    dataType: "html",
    data: {id: button_id},
    success: function(result){
        console.log(result);
        console.log(JSON.parse(result));
        var phparray = JSON.parse(result);
        var correct = phparray[12];   //<---This will return 100 
        var incorrect = phparray[13];  //<---This will return 10
        //I Dont know which one is your correct or incorrect column number but you can have an idea now
    }
});

请注意,我已将设置为break开关大小写内的strong>命令

尝试使用json.php获取javascript调用的json解析字符串。 下载链接:

Javascript中的更改:

   var getdata = function(button_id) {
        $.ajax({
            type: "POST",
            url: "../scripts/getdata.php",
            dataType: "json", // html -> json
            data: {id: button_id},
            success: function(result){

                $("#profilebox").html(result.html);

                return result;
            }
        });
    };

    function drawVisualization() {

        var data = getdata("profile_scores");

        // Create and populate the data table.
        var data = google.visualization.arrayToDataTable([
            ['', 'Correct', 'Incorrect'],
            ['Scores',  data.correct, data.incorrect],
        ]);

        var options = {
                'title': 'Total Scores Overall',
                'width': 600,
                'height': 400,
                'hAxis': {title: ''},
                'backgroundColor': 'transparent'
        };
        // Create and draw the visualization.
        new google.visualization.ColumnChart(document.getElementById('profilebox')).
        draw(data, options);
    };
getdata.php中的更改:

<?php
    // INCLUDE JSON
    // ----------------------------
    include_once("class.json.php");
    $json = new JSON();

    $coreJSON = array();
    // ----------------------------

    session_start();

    $switchcase = $_POST['id'];

    $email = $_SESSION['user']['email'];

    // call as result.html in javascript
    $coreJSON['html'] = ""; 
    // call as result.correct in javascript
    $coreJSON['correct'] = "";
    // call as result.incorrect in javascript
    $coreJSON['incorrect'] = "";

    //connect to database here
    $result=mysqli_query($con,"SELECT * FROM users WHERE email = '$email'");
    switch ($switchcase) {

        case "profile_home":  // <- CHANGES

            while($row = mysqli_fetch_array($result)) {

                $coreJSON['html'].= <<<EOF
                    {$row['username']}'s Profile<br /><br />
                    Name: {$row['firstname']} {$row['lastname']}<br /><br />
                    Things I like:<br>
                    {$row['like']} <br /><br />
                    Things I dislike:<br />
                    {$row['dislike']}<br /><br />
                    Other Sports:<br />
                    {$row['sports']}
EOF;
            }
            /* Start the closing EOF at the beginning of the line, and delete all spaces and tabs after the semicolon. Next code must start in a new line.*/

            break;

        case "profile_scores":

            while($row = mysqli_fetch_array($result)) {
                $coreJSON['correct'].= $row['correct']; // <- CHANGES
                $coreJSON['incorrect'].= $row['incorrect']; // <- CHANGES
            }

            break;
        case "profile_merits":
            //CODE GOES HERE;
            break;
        case "profile_help":
            //CODE GOES HERE;
            break;
        case "profile_edit":
            //CODE GOES HERE;
            break;
    }

    mysqli_close($con);

    // CLOSING AND CONVERTING
    // ----------------------------
    $encodeJSON = $json->encode($coreJSON);

    header('Content-Type: text/json'); // text/plain is good to
    header('Content-Length: '.strlen($encodeJSON));

    die($encodeJSON); 
    // ----------------------------
?>

你想用简单简单的语言陈述你想做什么吗?你得到你想要的了吗?ajax块中的success函数中必须包含“var phparray”、“var correct”和“var correct”?看看我更新的答案。如果您有任何疑问,请检查它。我在控制台中不断收到“未捕获引用错误:未定义正确”。我对这种类型的网络工作还很陌生:/如果你有任何问题,请在这里发表评论,而不是在你的问题中。我让它工作起来了,非常感谢,这帮了大忙。我遇到了一些错误,但我意识到我的一些功能可以组合在一起,这样它就可以工作了。
<?php
    // INCLUDE JSON
    // ----------------------------
    include_once("class.json.php");
    $json = new JSON();

    $coreJSON = array();
    // ----------------------------

    session_start();

    $switchcase = $_POST['id'];

    $email = $_SESSION['user']['email'];

    // call as result.html in javascript
    $coreJSON['html'] = ""; 
    // call as result.correct in javascript
    $coreJSON['correct'] = "";
    // call as result.incorrect in javascript
    $coreJSON['incorrect'] = "";

    //connect to database here
    $result=mysqli_query($con,"SELECT * FROM users WHERE email = '$email'");
    switch ($switchcase) {

        case "profile_home":  // <- CHANGES

            while($row = mysqli_fetch_array($result)) {

                $coreJSON['html'].= <<<EOF
                    {$row['username']}'s Profile<br /><br />
                    Name: {$row['firstname']} {$row['lastname']}<br /><br />
                    Things I like:<br>
                    {$row['like']} <br /><br />
                    Things I dislike:<br />
                    {$row['dislike']}<br /><br />
                    Other Sports:<br />
                    {$row['sports']}
EOF;
            }
            /* Start the closing EOF at the beginning of the line, and delete all spaces and tabs after the semicolon. Next code must start in a new line.*/

            break;

        case "profile_scores":

            while($row = mysqli_fetch_array($result)) {
                $coreJSON['correct'].= $row['correct']; // <- CHANGES
                $coreJSON['incorrect'].= $row['incorrect']; // <- CHANGES
            }

            break;
        case "profile_merits":
            //CODE GOES HERE;
            break;
        case "profile_help":
            //CODE GOES HERE;
            break;
        case "profile_edit":
            //CODE GOES HERE;
            break;
    }

    mysqli_close($con);

    // CLOSING AND CONVERTING
    // ----------------------------
    $encodeJSON = $json->encode($coreJSON);

    header('Content-Type: text/json'); // text/plain is good to
    header('Content-Length: '.strlen($encodeJSON));

    die($encodeJSON); 
    // ----------------------------
?>