Ajax函数发送GET请求,但PHP从不处理它

时间:2017-03-08 17:53:25

标签: javascript php ajax

我正在尝试使用Ajax在PHP脚本中运行一个函数。我的两个脚本文件如下:

get.js:

$.ajax({
    url: "testPhp.php",
    data: { param1: "INITIALIZE"},
    type: "GET",
    context: document.body
}).done(function() {
    alert("DONE!");
}).fail(function() {
    console.log(arguments);
});

testPhp.php:

<?php
    define("SERVER_NAME", "localhost");
    define("USERNAME", "root");
    define("PASSWORD", "");
    define("DATABASE", "myDB");

    //Print database info
    echo nl2br("Server Name: " . SERVER_NAME . "\nUsername: " . USERNAME .     "\nPassword: " . PASSWORD);

    //Connecting to database
    $mysqli = mysqli_connect(SERVER_NAME, USERNAME, PASSWORD);

    //Check database connection
    if($mysqli === false) {
        die ("\nCould not connect:  " . mysqli_connect_error());
    } else {
        echo nl2br("\nConnected successfully! Host info: " . mysqli_get_host_info($mysqli));
    }

    //Function to execute database queries
    function executeQuery($sql_query, $mysqli) {
        if(mysqli_query($mysqli, $sql_query)){
            echo nl2br("\n\nQuery executed successfully: $sql_query");
        } else {
            echo nl2br("\n\nERROR: Could not able to execute $sql_query. " . mysqli_error($mysqli));
        }
   }

    function initializeDatabase() {
        //Query to create flashcards database
        $sql = "CREATE DATABASE IF NOT EXISTS " . DATABASE;
        executeQuery($sql, $mysqli);
   }

   if(isset($_GET["param1"])) {
        $arg = $_GET["param1"];
        if($arg == "INITIALIZE") {
            initializeDatabase();
        }
    }

testPhp.php包含其他方法,但尚未调用任何方法。当我在函数外部运行代码为initializeDatabase()的PHP脚本时,它将自动运行,它完美地运行。加载我的网页后,在运行脚本的几秒钟后,alert()也会出现,因此在退出之前,它似乎在运行期间正在执行某些操作。但是,当我使用Ajax GET请求时,似乎PHP没有响应。有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

它可能失败,因为在函数platformA.belongsTo(connect, { foreignKey: 'id', as: 'platformAid' }); platformB.belongsTo(connect, { foreignKey: 'id', as: 'platformBid' }); 中,initializeDatabase()是未定义的变量。尝试将$mysqli传递给$mysqli