Форум программистов, компьютерный форум, киберфорум
PHP: базы данных
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.91/11: Рейтинг темы: голосов - 11, средняя оценка - 4.91
 Аватар для Ph_mx
0 / 0 / 0
Регистрация: 28.10.2012
Сообщений: 38

Связанные списки городов и стран (ajax, ActiveXObject)

23.09.2013, 02:34. Показов 2275. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
воспользовался чужой разработкой насчет связанных списков, но не пашет. никак не могу понять в чем траблы. прошу помощи.
P.S. подскажите заодно, пожалуйста, как можно обойтись в этом случае без ActiveXObject?

index.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?php 
 
include_once 'config.php';
echo '<script type="text/javascript" src="js/ajas.js"></script>';
echo '<script type="text/javascript" src="js/changes.js"></script>';
 
echo 'Страна:
<select id="country" name="country" onchange="getCountry(this)">
<option value="">Выберите страну...</option>';
$z_country=mysql_query("SELECT * FROM country");
    while ($country=mysql_fetch_array($z_country))
    {
    echo '<option value="'.$country['country_id'].'">'.$country['name'].'</option>';
    }
echo '</select><br/>';
echo 'Регион:
<select id="region" name="region" onchange="getRegion(this)">
<option value="">Выберите регион...</option>
</select><br/>';
echo 'Город:
<select id="city" name="city">
<option value="">Выберите город...</option>
</select>';
?>
changes.js
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var ajax = new Array();
function getCountry(sel)
{
    var country = sel.options[sel.selectedIndex].value;
    document.getElementById('region').options.length = 0;
    if(country.length>0){
        var index = ajax.length;
        ajax[index] = new sack();
        
        ajax[index].requestFile = 'ajas.php?country='+country;  
        ajax[index].onCompletion = function(){ createRegions(index) };  
        ajax[index].runAJAX();      
    }
}
function createRegions(index)
{
    var obj = document.getElementById('region');
    eval(ajax[index].response); 
}
function getRegion(sel)
{
    var region = sel.options[sel.selectedIndex].value;
    document.getElementById('city').options.length = 0; 
    if(region.length>0){
        var index = ajax.length;
        ajax[index] = new sack();
        
        ajax[index].requestFile = 'ajas.php?region='+region;    
        ajax[index].onCompletion = function(){ createCity(index) }; 
        ajax[index].runAJAX();      
    }
}
function createCity(index)
{
    var obj = document.getElementById('city');
    eval(ajax[index].response); 
}
ajas.php
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
 
if(isset($_GET['country'])){
include_once 'connect.php'; 
  switch($_GET['country']){
    case $_GET['country']:
    $z_region=mysql_query("SELECT * FROM region WHERE country_id='".$_GET['country']."' ");
    while ($region=mysql_fetch_array($z_region))
    {
    echo "obj.options[obj.options.length] = new Option('".$region['name']."','".$region['region_id']."');\n";
    }
  }
} 
if(isset($_GET['region'])){
include_once 'connect.php'; 
  switch($_GET['region']){
    case $_GET['region']:
    $z_city=mysql_query("SELECT * FROM city WHERE region_id='".$_GET['region']."' ");
    while ($city=mysql_fetch_array($z_city))
    {
    echo "obj.options[obj.options.length] = new Option('".$city['name']."','".$city['city_id']."');\n";
    }
  }
}
?>

ajas.js
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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();
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
23.09.2013, 02:34
Ответы с готовыми решениями:

Связанные списки Ajax + PHP
Здраствуйте форумчани уже больше месяца долблю себе мозг как сделать связанные выпадающие списки, сделать два селекта получилось, но в...

Связанные списки ajax+php
Сделал 2 связанных списка, но не понимаю как привязать третий, буду благодарен любой помощи. Index.php &lt;? define('DB_HOST',...

Как сделать связанные выпадающие списки mysql + ajax ?
Как сделать связанные выпадающие списки mysql + ajax ?

1
 Аватар для Ph_mx
0 / 0 / 0
Регистрация: 28.10.2012
Сообщений: 38
24.09.2013, 13:40  [ТС]
Друзья, вопрос остается открытым. помогите пожалуйста
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
24.09.2013, 13:40
Помогаю со студенческими работами здесь

Связанные выпадающие списки с записями из базы данных JQuery-AJAX + PHP
Добрый день! Требуется на сайте для стоматологического кабинета создать скрипт для связанных выпадающих списков. При выборе врачебной...

базы стран и городов
на многих сайтах при регистрации например появляются два три комбобокса, в первом страны, вебераем страну во втором появляются города,...

База стран и городов
Проблемма вот в чем. скачиваю из нета подобную базу, открываю, а там вместо кирилицы какието кракозябры! ОС у меня англо-иврито язычная! ...

Правильная подстановка стран и городов
Добрый день. У меня есть таблица с турами. У каждого тура есть поле: &quot;страна&quot; и &quot;город&quot;. Я хочу сделать так, чтобы при...

Нужен дамп БД стран и городов (мультиязычный желательно)
Добрый Вечер. Разрабатываю ресурс - и мне при регистрации человек должен выбрать страну а после этого должны подгрузиться города этой...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Символьное дифференцирование
igorrr37 13.02.2026
/ * Логарифм записывается как: (x-2)log(x^2+2) - означает логарифм (x^2+2) по основанию (x-2). Унарный минус обозначается как ! */ #include <iostream> #include <stack> #include <cctype>. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL3_image
8Observer8 10.02.2026
Содержание блога Библиотека SDL3_image содержит инструменты для расширенной работы с изображениями. Пошагово создадим проект для загрузки изображения формата PNG с альфа-каналом (с прозрачным. . .
Установка Qt-версии Lazarus IDE в Debian Trixie Xfce
volvo 10.02.2026
В общем, достали меня глюки IDE Лазаруса, собранной с использованием набора виджетов Gtk2 (конкретно: если набирать текст в редакторе и вызвать подсказку через Ctrl+Space, то после закрытия окошка. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru