2013-04-29 54 views
-2

我正在使用MagicSuggest自動完成標籤。 此代碼的工作完美:MagicSuggest以PHP失敗

$(document).ready(function() { 
     var ms3 = $('#ms3').magicSuggest({ 
      data: [{id:12,name:'php'},{id:1212,name:'java'},{id:112,name:'python'},{id:125,name:'html'},{id:172,name:'css'}] 
     }); 
    }); 

但是這一次沒有:

$(document).ready(function() { 
     var ms3 = $('#ms3').magicSuggest({ 
      data:'data.php' 
     }); 
    }); 

PHP:

<?php 
      echo "[{id:12,name:'php'},{id:1212,name:'java'},{id:112,name:'python'},{id:125,name:'html'},{id:172,name:'css'}]"; 
    ?> 

附:這適用於data:'data.json'內部帶有json數據的情況。

+1

http://stackoverflow.com/questions/15488053/magicsuggest-dynamic-ajax-source – Robert 2013-04-29 10:25:53

回答

0

你爲什麼不......

<?php 
    $mydata = "[{id:12,name:'php'},{id:1212,name:'java'},{id:112,name:'python'},{id:125,name:'html'},{id:172,name:'css'}]"; 
?> 

$(document).ready(function() { 
    var ms3 = $('#ms3').magicSuggest({ 
     data: <?php echo$mydata;?> 
    }); 
}); 

這樣,你可以從一個數據庫查詢填充$mydata數據等

OR

嘗試在你的data.php文件follwing;

<?php 
    header('Content-type: application/json'); 
    echo "[{id:12,name:'php'},{id:1212,name:'java'},{id:112,name:'python'},{id:125,name:'html'},{id:172,name:'css'}]"; 
?> 
+0

'data:<?php echo $ mydata;?>'即使這個查詢是數百行? – dcclassics 2014-04-03 02:57:55

1

我認爲這個問題可能是PHP文件返回錯誤的MIME類型的事實。 試着在你data.php文件的頂部添加此
header('Content-type: application/json');

所以你data.php文件看起來像

<?php 
    header('Content-type: application/json'); 
    echo "[{id:12,name:'php'},{id:1212,name:'java'},{id:112,name:'python'},{id:125,name:'html'},{id:172,name:'css'}]"; 
?> 
1

在JSON規範不presend單引號 - 你必須改變對雙引號

更好的是你可以使用json_encode功能

header('Content-type: application/json'); 
echo json_encode(array(
    array('id'=>12, 'name'=> 'php') 
));