当我在localhost上使用select2和我的数据库时。它工作正常。 但是当我在服务器上使用数据库时,例如10.0.0.1它不起作用。
这是我的select2脚本:
$('#slDrug').select2({
placeholder: 'ค้นหาเวชภัณฑ์',
minimumInputLength: 1,
allowClear: true,
language: "th",
ajax: {
url: 'ajax/drugSearch.php',
dataType: 'JSON',
type: 'GET',
quietMillis: 100,
data: function (term, page) {
return {
query: term,
start: page,
stop: 20
};
}, results: function (data, page) {
var more = (page * 10) < data.total;
return { results: data.rows, more: more };
}
}, id: function(data) {
return { id: data.code }
}, formatResult: function(data) {
return '[ ' + data.code + ' ] ' + data.name + ' ความแรง : ' + data.strength + ' หน่วยนับ : ' + data.units;
}, formatSelection: function(data) {
return data.code + ' ' + data.name + ' ' + data.strength;
}
});
这是我的PHP代码:
<?php
require_once('../require/medoo.min.php');
// Select connectinfo from database
$localDB = new medoo();
$getHosInfo = $localDB->select("sys_config","*");
foreach($getHosInfo as $g){
$host = $g['host'];
$user = $g['user'];
$pass = $g['password'];
$dbname = $g['dbname'];
}
header('Content-type: text/html; charset=utf-8');
$dsn = 'mysql:host='.$host.'; dbname='.$dbname.'; charset=utf8';
try {
$conn = new PDO( $dsn, $user, $pass);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo 'Connection failed: ' . $e->getMessage();
}
$query = $_GET['query'];
$callback = $_GET['callback'];
$start = $_GET['start'];
$stop = $_GET['stop'];
$start = empty($start) ? 1 : $start;
$stop = empty($stop) ? 10 : $stop;
$start = ($start - 1) * $stop;
$sql_total = 'select count(*) as total from drugitems where name like "%' . $query . '%"';
$st = $conn->prepare($sql_total);
$st->execute();
$rows_total = $st->fetch();
$sql_rows = 'select icode, name, strength,units,unitcost,unitprice,did,antibiotic,fp_drug
from drugitems
where name like "%' . $query . '%" limit ' . $start . ', ' . $stop;
$st = $conn->prepare($sql_rows);
$st->execute();
$rows_result = $st->fetchAll();
$data = array();
foreach($rows_result as $r)
{
$obj = new stdClass();
$obj->code = $r['icode'];
$obj->name = $r['name'];
$obj->strength = $r['strength'];
$obj->did = $r['did'];
$obj->unitprice = $r['unitprice'];
$obj->unitcost = $r['unitcost'];
$obj->units = $r['units'];
$obj->antibiotic = $r['antibiotic'];
$obj->fp_drug = $r['fp_drug'];
$data[] = $obj;
}
$json = '{"ok": 1, "total": ' . $rows_total['total'] . ', "rows": ' . json_encode($data) . '}';
echo $callback . '(' . $json . ')';
?>