2013-08-06 39 views
0

好的,我有以下幾點。當用戶將某些東西放入文本字​​段然後失去焦點時,會發出ajax請求。JSON獲得的警報結果

$(document).ready(function() { 
//On Focus lose get content of the first input field 
$('#fromCountry').blur(function() 
{ 
    var input = $('#fromCountry').val(); 
    if(input == "") 
     return false; 
    else 
    { 
     $.ajax({ 
       type: 'GET', 
       url: 'webservice.php', 
       data: {country: input, action: 'firstTime'}, 
       success: function(response, textStatus, XMLHttpRequest) { 
        alert("TEST"); 
       } 
      } 
     ); 
    } 
}); 
}); 

然後,將請求發送到與該國的WebService鍵入到這個領域和Web服務使用從數據庫類的方法來獲得該國的經度和lattitude(該國首都的),並將它作爲JSON

這是webservice.php

<?php 
header("Content-type: application/json"); 
require('Database.php'); 
$db = new Database(); 

$action = $_GET['action']; 
if($action == 'firstTime') 
{ 
    $country = $_GET['country']; 
    $result = $db->getLocation($country); 
    echo json_encode($result); 
} 
?> 

,這是數據庫類

<?php 
error_reporting(E_ALL); 
ini_set('display_errors', 1); 
class Database { 
private $user = "root"; 
private $pw = ""; 
public $pdo = null; 

public function __construct($new = FALSE){ 
    try{ 
     $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=timezone',$this->user, $this->pw); 
     $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
    } 
    catch(PDOException $e){ 

    } 
} 
public function __call($name, array $arguments) { 

    if(method_exists($this->pdo, $name)){ 
     try{ 
      return call_user_func_array(array(&$this->pdo, $name), $arguments); 
     } 
     catch(Exception $e){ 
      throw new Exception('Database Error: "'.$name.'" does not exists'); 
     } 
    } 
} 

function getLocation($country) 
{ 
    $SQL = "SELECT cLat, cLon FROM countries WHERE cName = :cName"; 
    $prepare = $this->prepare($SQL); 
    $prepare->bindParam(':cName', $country); 
    $prepare->execute(); 
    $result = $prepare->fetch(); 
    var_dump($result); 
    return $result; 
} 

}

當我現在在瑞典類型。例如,我得到這個作爲XHR響應

array(2) { 
    ["cLat"]=> 
    string(10) "59.3333333" 
    ["cLon"]=> 
    string(5) "18.05" 
} 

這基本上是正確的,但我的AJAX功能不提醒「TEST」,因爲它是因爲它應該在成功功能。我忘了一步嗎?

-----編輯:

我現在又增加

, 
       error: function(){ 
        alert("ERROR"); 
       } 

,它總是進入錯誤的功能,但是爲什麼呢?我的意思是,它根據螢火蟲得到了迴應,所以錯誤在哪裏?

+0

你知道什麼HTTP代碼的反應是變量? – MajorCaiger

回答

0

變化

function(response, textStatus, xhr) { 

XMLHttpRequest是一個類的名字,你不能說出這樣的

+0

嗨,我改變了它,但它仍然沒有提示測試。它以某種方式不能進入成功功能。我現在加了', 錯誤:function(){ alert(「ERROR」); }'它進入錯誤函數,但爲什麼? – loomie

+0

你有沒有安裝螢火蟲?檢查控制檯中發生了什麼。可能你得到一些HTTP錯誤,如404或403 – Hubu

+0

正如我所說的螢火蟲XHR告訴我我上面張貼的代碼。 – loomie