2013-03-25 143 views
0

我需要附加jquery函數的結果。 當用戶鍵入搜索字段時,會調用一個函數,並從我的數據庫返回數據。 我可以使用提醒功能看到返回的數據jquery自動完成onkey功能

<input type="text" name="symbol" id="symbol" required="required" onkeyup="findmatch();"> 

稱爲jQuery函數低於

function findmatch(){ 
    var symbol= document.getElementById("symbol").value; 

    $.post("portfolio/searchStock.php", 
    { 
     search:symbol 
    }, 
    function(data,status){ 
    alert(data); 

    });  
} 

我需要把數據返回給被像自動完整而我一直在使用中的以下嘗試的功能,我不明白爲什麼它不工作

$("#symbol").autocomplete({ 
       source: data 
     }); 

PHP文件的回聲數據如下

if (isset ($_POST['search'])){ 

$ search = $ _POST ['search']; if(!empty($ search)){ $ query =「select * from companylist where symbol like'」.mysql_real_escape_string($ search)。「%'」; $ query_run = mysql_query($ query);

while ($query_row = mysql_fetch_assoc($query_run)){ 
     $symbol = $query_row['symbol']; 
     echo $symbol; 
    } 
} 

}

+0

你能也粘貼在返回數據的格式? – 2013-03-25 14:34:10

回答

0

您需要格式化數據庫調用的輸出:

while ($query_row = mysql_fetch_assoc($query_run)){ 
    $symbol[] = $query_row['symbol']; 
} 
echo json_encode($symbol); 

然後,你需要分析返回的數據。

var sourceData = []; 
var arrData = $.parseJSON(data); 
foreach(x in arrData) 
{ 
    sourceData.push(arrData[x]); 
} 
$("#symbol").autocomplete({ 
      source: sourceData 
}); 
+0

他還需要記住他的數據需要格式化爲:[{label:「Choice1」,value:「value1」},...]或[「Choice1」,「Choice2」] – 2013-03-25 14:31:50

+0

感謝提醒,編輯答案。 – 2013-03-25 15:47:23

+0

謝謝你,需要等3個小時才能發佈我的答案,因爲我是新來的。 – user2202098 2013-03-25 19:04:14

0

試試這個

$("#symbol").autocomplete({ 
       'search':function(event,ui){ 
       var newUrl="portfolio/searchStock.php/abc/"+$("#symbol").val(); 
       $(this).autocomplete("option","source",newUrl) 
       }, 
       'source':[] 
    }); 

,並在PHP

function abc($search){ 


if(!empty ($search)){ $query="select * from companylist where symbol like '".mysql_real_escape_string($search)."%'"; $query_run = mysql_query($query); 

    while ($query_row = mysql_fetch_assoc($query_run)){ 

     $new_row['label']=htmlentities(stripslashes($query_row['symbol'])); 
    $new_row['value']=htmlentities(stripslashes($query_row['symbol_id'])); 
    $row_set[] = $new_row; //build an array 
    } 

}echo json_encode($row_set); 
} 
0

謝謝你的回信,這似乎工作。陣列所需編碼並從PHP側 解析JavaScript文件

function findmatch(){ 
    var symbol= document.getElementById("tSymbol").value; 
    $.post("portfolio/searchStock.php", 
    { 
     search:symbol 
    }, 
    function(data,status){ 
    var arrData = $.parseJSON(data); 
    $("#tSymbol").autocomplete({ 
     source: arrData 
    }); 
    });  
} 

searchStock.php

if (isset ($_POST['search'])){ 

$查詢= $ _POST [ '搜索']; if(!empty($ search)){ $ query =「select * from companylist where symbol like'」.mysql_real_escape_string($ search)。「%'」; $ query_run = mysql_query($ query);

while ($query_row = mysql_fetch_assoc($query_run)){ 
     $symbol [] = $query_row['symbol']; 

    } 
    echo json_encode($symbol); 


} 

}