我有一个功能正常的php应用程序,它完美地使用了AutoSuggest JS脚本,现在我正在将相同的应用程序移植到codeigniter中。我不太擅长CI,所以我想试试这个。问题是它不起作用。代码如下:
JS部分 var options = {
script:"/getPartnerLogo?",
varname:"input",
json:true,
shownoresults:false,
maxresults:6,
callback: function (obj) { document.getElementById('partner1').value = obj.info;
}
};
var as_json = new bsn.AutoSuggest('pt1', options);
控制器上的代码
function getPartnerLogo(){
$aUsers = array(
"HSBC",
"Spinneys"
);
$aInfo = array(
"HSB",
"SPN"
);
$input = trim($this->input->get('input'));
$len = strlen($input);
$limit = 6;
$aResults = array();
$count = 0;
if ($len)
{
for ($i=0;$i<count($aUsers);$i++)
{
if (strtolower(substr(utf8_decode($aUsers[$i]),0,$len)) == $input)
{
$count++;
$aResults[] = array( "id"=>($i+1) ,"value"=>htmlspecialchars($aUsers[$i]), "info"=>htmlspecialchars($aInfo[$i]) );
}
if ($limit && $count==$limit)
break;
}
}
header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header ("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); // always modified
header ("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header ("Pragma: no-cache"); // HTTP/1.0
header("Content-Type: application/json");
echo "{'"results'": [";
$arr = array();
for ($i=0;$i<count($aResults);$i++)
{
$arr[] = "{'"id'": '"".$aResults[$i]['id']."'", '"value'": '"".$aResults[$i]['value']."'", '"info'": '"".$aResults[$i]['info']."'"}";
}
echo implode(", ", $arr);
echo "]}";
}
}
现在当我直接访问控制器时,它会正确返回json。
http://localhost/cd/getPartnerLogo?input=h
{"结果":[{" id ":"3","价值":"汇丰银行","信息":"HSB"}]}
但是当我尝试从JS它给了我一个404错误。当我跟踪网络调用form inspect元素时,响应是来自CI的默认404错误页面。
有谁能帮我解决这个问题吗
检查您的请求URL。
大多数时候,当您在localhost上工作时,由于URL中的一些错误,ajax请求失败。
例如,您的脚本在localhost/dc
下,但您的ajax请求发送到localhost/
。你可以在本地主机上配置虚拟主机和设置域名,或者在所有ajax请求上设置基本url,但必须是绝对url。要检查您的请求去哪里,您可以在开发工具下的firefox/chrome网络选项卡中检查它们。