2014-04-11 86 views
0

我有一個應用程序,允許用戶從jQuery自動填充框中選擇一個活動(如看電影或合氣道)。這部分工作。然而,我想要的是一些盒子,允許用戶選擇他們的專業知識,如果專業知識不相關(例如看電影),或者如果專業知識相關,則可以使其失效。爲此,我試圖從自動完成選擇事件中調用$ .getJSON。 $ .getJSON調用服務器端php腳本,詢問mysql數據庫是否剛剛選擇的活動需要專業知識。但它似乎並沒有調用$ .getJSON。jQuery自動完成選擇調用服務器端腳本

這裏是我的HTML:

<label for="activity">Select Activity:</label> 
<input id="activity"> 

這裏是我的javascript:

$("#activity").autocomplete({ 
    minLength: 2, 
    source: "php/getActivities.php", 
    select: function(event, ui) { 

     // Call the server side script to determine whether or not this activity 
     // requires expertise or not 
     queryString = 'activity=' + encodeURIComponent(ui.item.value); 
     alert (queryString); 

     $.getJSON('php/checkActivityExpertise.php',queryString,function(data2) { 

      alert('in .getJSON'); 

      if (data2.needExpertise) { 
       activateBoxes(); 
      } 
      else { 
       deactivateBoxes(); 
      } 

     }); // end of $.getJSON call 
    } // end of select: function 
}); // end of activity.autocomplete 

而這裏的PHP函數:

<?php // checkActivityExpertise.php 

// Connect to database 
include_once 'dbConnect.php'; 
include_once 'sanitizeString.php'; 

$activity = sanitizeString($_GET['activity']); 

// query database on whether or not expertise is needed 
$query = "SELECT displayExpertise FROM activities WHERE activity=$activity"; 
$resource = mysql_query($query); 
$row = mysql_fetch_row($resource); 
$needExpertise = $row[0]; 

// Return the flags back to calling function 

$arr = array('needExpertise' => $needExpertise); 

echo json_encode($arr); 

?> 

警報(的queryString);作品發現 - 所以它得到這麼多。警報('in .getJSON');但是沒有工作。我嘗試過註釋掉所有的PHP函數 - 所以我想知道如果我不能從自動完成選擇事件中調用$ .getJSON?

感謝,

湯姆

回答

1

很難知道什麼是錯的,我會做的是爲不同的狀態添加處理程序,特別是fail的情況下:

$.getJSON('php/checkActivityExpertise.php',queryString,function(data2) { 
    alert('in .getJSON'); 
    if (data2.needExpertise) { 
     activateBoxes(); 
    } 
    else { 
     deactivateBoxes(); 
    } 
}).done(function() { 
    alert("done"); 
}) 
.fail(function(jqxhr, textStatus, error) { 
    var err = textStatus + ", " + error; 
    alert("Request Failed: " + err); 
}) 
.always(function() { 
    alert("always"); 
}).complete(function() { 
    alert("complete"); 
}); 
+0

謝謝。我做到了。它給我的錯誤:「請求失敗:parsererror,SyntaxError:意外的令牌<」不知道爲什麼會發生錯誤? – Tom78

+0

什麼是你的querystring? – Starscream1984

+0

查詢字符串是「活動=合氣道」(舉例來說,活動取決於用戶在文本框中輸入的內容) – Tom78

0

所以不會觸發做處理getJSON()可能會返回一個錯誤 - 使用這個模式,而不是從文檔

var jqxhr = $.getJSON("example.json", function() { 
    console.log("success"); 
}) 
.done(function() { 
    console.log("second success"); 
}) 
.fail(function() { 
    console.log("error"); 
}) 
.always(function() { 
    console.log("complete"); 
}); 

所以你可以把警報並看看通話的結果是什麼