PHP函数没有被调用,我错过了一些明显的东西吗?

Som*_*per 2 php ajax jquery function

我想我需要第二双眼睛.

我有一些调用php文件的ajax,它正在返回json.一切正常.然后我警告我返回的数据元素用于测试目的.在这样做,我缩小了我的功能是没有被调用.

<?php

// database functions
$response = array();
$count = 1;

// connect to db
function connect() {   
$response['alert'] = 'connect ran'; // does not get alerted
}

// loop through query string
foreach ($_POST as $key => $value) {

switch ($key) {
    case 'connect':
        $response['alert'] = 'case ran';
        if ($value == 'true') {
        $response['alert'] = 'if ran'; // this is what gets alerted, should be overwriten by 'connect ran'
            connect(); // function call does not work?
        } else {
            $response['alert'] = 'false';
            $mysqli->close();
        }
        break;

        case 'otherstuff':
        break;
}
++$count;
}

$response['count'] = $count;

echo json_encode($response);

?>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢.

vlc*_*mi3 6

你的$response变量超出范围 .. global在你的函数中使用关键字来注册你的外部变量

function connect() {
    global $response;    
    $response['alert'] = 'connect ran';
}
Run Code Online (Sandbox Code Playgroud)

或SDC的编辑:

function connect($response) { 
    $response['alert'] = 'connect ran';
}

connect($response);
Run Code Online (Sandbox Code Playgroud)