2012-12-07 34 views
2

我想我需要第二雙眼睛。PHP函數沒有被調用,我錯過了一些明顯的東西?

我有一些ajax調用一個php文件,它返回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); 

?> 

任何想法?謝謝。

+2

您可能需要考慮傳遞$ response來連接,然後返回它而不是實現global關鍵字。 – thescientist

回答

6

$response變量超出scope ..用你的函數內部global關鍵字來註冊你的外在變量(一個或多個)

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

或SDC的編輯:

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

connect($response); 
+0

或更好,然後將它作爲參數傳遞給函數;儘可能避免使用全局變量。 – SDC

0

其實你定義的結果變量但是在另一種類型中,並且在頂部還有另一個結果變量,所以您將數據放在$ result []中,但是您嘗試使用$ result,因此您的代碼可能不會給您預期的結果。

相關問題