|
|
|
| Всем привет! Бьюсь с автозаполнением уже второй день. Прочитал кучу тем по поводу кодировок и т.д. Но к сожалению все равно не получается!
В базе содержаться наименования стран на английском и русском языках!
Подсобите, пож-та:
Имеется форма:
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript" src="js/ajax-dynamic-list.js">
</script>
<form>
<table border="0">
<tr>
<td><label for="country">Country: </label></td>
<td><input type="text" size="80" id="country" name="country" value="" onkeyup="ajax_showOptions(this,'getCountriesByLetters',event)">
<input type="text" id="country_hidden" name="country_ID"></td>
</tr>
</form>
|
И есть обработчик php:
header("Content-type: text/plain; charset=windows-1251");
$conn = mysql_connect("","","");
mysql_query("SET NAMES UTF-8");
mysql_select_db("squidlog",$conn);
if(isset($_GET['getCountriesByLetters']) && isset($_GET['letters']))
{
$letters= iconv('UTF-8', 'windows-1251',$_GET['letters']);
$res = mysql_query("select ID,countryName from ajax_countries where countryName like '".$letters."%'") or die(mysql_error());
while($inf = mysql_fetch_array($res))
{
echo $inf["ID"]."###".$inf["countryName"]." ".$inf["name"]."|".$letters;
}
}
|
В результате получается - если вводишь англ. буквы поиск осуществляется при этом наименования стран на русском отображаются крокозяблями,типа:
Р?спания
Р РѕСЃСЃРёСЏ
Подскажите что не так! | |
|
|
|
|
|
|
|
для: Front
(03.04.2008 в 12:13)
| | В случае если закомментируешь строку:
header("Content-type: text/plain; charset=windows-1251");
Кракозябли пропадают, но дело в том что поиск в соответствии с вводимыми словами все равно не осущеставляется! | |
|
|
|
|
|
|
|
для: Front
(03.04.2008 в 12:19)
| | уже не раз обсуждалось:
Перед отправкой данных обратно нужно поменять кодировку:
$var= iconv('utf-8', 'windows-1251',$var);
|
| |
|
|
|
|
|
|
|
для: Antohins
(03.04.2008 в 13:39)
| | Так а где ее нужно менять?
Вот так:
while($inf = mysql_fetch_array($res))
{
$var = $inf["ID"]."###".$inf["countryName"]." ".$inf["name"]."|".$letters;
$var= iconv('utf-8', 'windows-1251',$var);
echo $var;
}
|
| |
|
|
|
|
|
|
|
для: Front
(03.04.2008 в 13:43)
| | если означает вывод в frontend файле (т.е. из того, откуда пришли данные и где выводится результат), то да. | |
|
|
|
|
|
|
|
для: Antohins
(03.04.2008 в 13:51)
| | Кракозябли пропали, но дело в том что при вводе русских букв соответствия не находится, просто выгружаются полностью все строки таблицы из базы данных! В чем может быть проблема?
Может быть проблема с передачей переменной letters?
Сделал такую проверку?
$r = "select ID,countryName from ajax_countries where countryName like '".$letters."%'";
$res = mysql_query("select ID,countryName from ajax_countries where countryName like '".$letters."%'") or die(mysql_error());
#echo "1###select ID,countryName from ajax_countries where countryName like '".$letters."%'|";
while($inf = mysql_fetch_array($res))
{
$var = $inf["ID"]."###".$inf["countryName"]." ".$inf["name"]."|".$r;
$var= iconv('utf-8', 'windows-1251',$var);
echo $var;
}
|
При вводе английских букв (например Russi) волучается такой запрос:
select ID,countryName from ajax_countries where countryName like 'russi%'
|
А при вводе русских (например Россия) получается такой запрос:
select ID,countryName from ajax_countries where countryName like '%'
|
Получается что переменная пустая? | |
|
|
|
|
|
|
|
для: Front
(03.04.2008 в 14:00)
| | Возможно поможет запрос
mysql_query("SET NAMES 'cp1251'");
|
поставьте его сразу после соединения с бд.
Если это не поможет - выложите код, который отсылает и принимает данные. | |
|
|
|
|
|
|
|
для: Antohins
(03.04.2008 в 14:47)
| | Нет! Не помогло запрос остается таким же, т.е. переменная $letters пустая!
Код передачи и приема!
ajax.js:
function sack(file) {
this.xmlhttp = null;
this.resetData = function()
{
this.method = "POST";
this.queryStringSeparator = "?";
this.argumentSeparator = "&";
this.URLString = "";
this.encodeURIString = true;
this.execute = false;
this.element = null;
this.elementObj = null;
this.requestFile = file;
this.vars = new Object();
this.responseStatus = new Array(2);
};
this.resetFunctions = function() {
this.onLoading = function() { };
this.onLoaded = function() { };
this.onInteractive = function() { };
this.onCompletion = function() { };
this.onError = function() { };
this.onFail = function() { };
};
this.reset = function() {
this.resetFunctions();
this.resetData();
};
this.createAJAX = function() {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
if (! this.xmlhttp) {
if (typeof XMLHttpRequest != "undefined") {
this.xmlhttp = new XMLHttpRequest();
} else {
this.failed = true;
}
}
};
this.setVar = function(name, value){
this.vars[name] = Array(value, false);
};
this.encVar = function(name, value, returnvars) {
if (true == returnvars) {
return Array(encodeURIComponent(name), encodeURIComponent(value));
} else {
this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
}
}
this.processURLString = function(string, encode) {
encoded = encodeURIComponent(this.argumentSeparator);
regexp = new RegExp(this.argumentSeparator + "|" + encoded);
varArray = string.split(regexp);
for (i = 0; i < varArray.length; i++){
urlVars = varArray[i].split("=");
if (true == encode){
this.encVar(urlVars[0], urlVars[1]);
} else {
this.setVar(urlVars[0], urlVars[1]);
}
}
}
this.createURLString = function(urlstring) {
if (this.encodeURIString && this.URLString.length) {
this.processURLString(this.URLString, true);
}
if (urlstring) {
if (this.URLString.length) {
this.URLString += this.argumentSeparator + urlstring;
} else {
this.URLString = urlstring;
}
}
// prevents caching of URLString
this.setVar("rndval", new Date().getTime());
urlstringtemp = new Array();
for (key in this.vars) {
if (false == this.vars[key][1] && true == this.encodeURIString) {
encoded = this.encVar(key, this.vars[key][0], true);
delete this.vars[key];
this.vars[encoded[0]] = Array(encoded[1], true);
key = encoded[0];
}
urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
}
if (urlstring){
this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
} else {
this.URLString += urlstringtemp.join(this.argumentSeparator);
}
}
this.runResponse = function() {
eval(this.response);
}
this.runAJAX = function(urlstring) {
if (this.failed) {
this.onFail();
} else {
this.createURLString(urlstring);
if (this.element) {
this.elementObj = document.getElementById(this.element);
}
if (this.xmlhttp) {
var self = this;
if (this.method == "GET") {
totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
this.xmlhttp.open(this.method, totalurlstring, true);
} else {
this.xmlhttp.open(this.method, this.requestFile, true);
try {
this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
} catch (e) { }
}
this.xmlhttp.onreadystatechange = function() {
switch (self.xmlhttp.readyState) {
case 1:
self.onLoading();
break;
case 2:
self.onLoaded();
break;
case 3:
self.onInteractive();
break;
case 4:
self.response = self.xmlhttp.responseText;
self.responseXML = self.xmlhttp.responseXML;
self.responseStatus[0] = self.xmlhttp.status;
self.responseStatus[1] = self.xmlhttp.statusText;
if (self.execute) {
self.runResponse();
}
if (self.elementObj) {
elemNodeName = self.elementObj.nodeName;
elemNodeName.toLowerCase();
if (elemNodeName == "input"
|| elemNodeName == "select"
|| elemNodeName == "option"
|| elemNodeName == "textarea") {
self.elementObj.value = self.response;
} else {
self.elementObj.innerHTML = self.response;
}
}
if (self.responseStatus[0] == "200") {
self.onCompletion();
} else {
self.onError();
}
self.URLString = "";
break;
}
};
this.xmlhttp.send(this.URLString);
}
}
};
this.reset();
this.createAJAX();
}
|
На всякий случай вложил еще файл ajax-dynamic-list.js | |
|
|
|
|
|
|
|
для: Front
(03.04.2008 в 15:08)
| | Товарищи, ну что никто не знает как решить проблему? :-( | |
|
|
|
|
|
|
|
для: Front
(03.04.2008 в 15:08)
| | ужс. юэай jquery | |
|
|
|
|
|
|
|
для: Antohins
(04.04.2008 в 12:35)
| | Поподробнее возможно, в чем ужс, что не так? | |
|
|
|