Как подставить переменную в URL при отправке через ajax?
Я получаю параметр Click ID таким способом:
<span id="cl_id" class="password-span" style="visibility: hidden"><?php echo htmlspecialchars($_GET["clickid"]);?></span>
Как мне подставить полученный Click ID сюда (вместо CLICK ID)?:
xhr = new XMLHttpRequest();
xhr.open('GET', `http://Ваш_сервер/*CLICK ID*`);
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.send();
Ответы (2 шт):
Автор решения: Alexandr
→ Ссылка
Очень просто:
HTML
вместо:
<span id="cl_id" class="password-span" style="visibility: hidden">
<?php echo htmlspecialchars($_GET["clickid"]);?>
</span>
это:
<script>
var cl_id = `<?php echo htmlspecialchars($_GET["clickid"]);?>}`;
</script>
JS:
xhr = new XMLHttpRequest();
xhr.open('GET', `http://Ваш_сервер/${cl_id}`);
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.send();
Должно помочь
Автор решения: skatch mast
→ Ссылка
если сам скрипт ajax находится в отдельном файле то нужно зарание определить переменную
<script>
var clId = '<?=htmlspecialchars($_GET["clickid"])?>'
</script>
или
<script>
var clId = '<?php echo htmlspecialchars($_GET["clickid"]); ?>'
</script>
затем подставить в запрос
xhr = new XMLHttpRequest();
xhr.open('GET', 'http://Ваш_сервер/' + clId);
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.send();
но если скрипт находится прямо в файле php
то можно так
<script>
xhr = new XMLHttpRequest();
xhr.open('GET', `http://Ваш_сервер/<?=htmlspecialchars($_GET["clickid"])?>`);
xhr.onload = function() {
console.log(xhr.responseText);
};
xhr.send();
</script>