好的,我有以下幾點。當用戶將某些東西放入文本字段然後失去焦點時,會發出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");
}
,它總是進入錯誤的功能,但是爲什麼呢?我的意思是,它根據螢火蟲得到了迴應,所以錯誤在哪裏?
你知道什麼HTTP代碼的反應是變量? – MajorCaiger