我實現GEONAMES web服務,像這樣:檢查一個MySQL領域存在創造如果沒有
$("#loc_from").autocomplete({
source: function(request, response) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term,
searchlang: 'ES'
},
success: function(data) {
response($.map(data.geonames, function(item) {
item.label = item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName;
return item;
}));
}
});
},
minLength: 2,
select: function(event, ui) {
ui.item.task = 'new_city';
$.post('/includes/router.php', ui.item , function(){
});
$('#id_loc').val(ui.item.gid);
//alert(ui.item.gid);
}
});
其中router.php我:
case 'new_city':
/* comprobar si exite */
$query = "SELECT geonameid FROM geonames";
if(count(cache_query($query))>0){
/* Its already in my database */
}else{
foreach ($_POST as $key => $value) {
check_field($key);
echo $key.': '.$value.'<br>';
}
}
/* si no existe, dar de alta*/
break;
所以我想函數check_field($key)
來檢查geonames。$ key字段是否存在,並修改表並添加它。
這是可行嗎? (另外,你建議嗎?)
爲什麼不在編寫代碼之前在MySQL表中添加鍵字段?要回答你的問題,是的,它可以完成,但這是一個不好的方法。 – Achrome
因爲響應每次都會返回不同的字段 –