Если вашему AJAX-сценарию требуется более пары миллисекунд, eval () всегда будет выполняться вперед и оценивать пустой элемент ответа, прежде чем AJAX заполнит его сценарием, который вы пытаетесь выполнить.
Вместо того, чтобы возиться с таймингом и eval (), здесь есть довольно простой обходной путь, который должен работать в большинстве ситуаций и, вероятно, немного более безопасен. Использование eval () обычно не одобряется, потому что символы, оцениваемые как код, могут легко манипулироваться на стороне клиента.
Концепция
- Включите вашу функцию JavaScript на главной странице. Запишите его так, чтобы любые динамические элементы могли быть приняты в качестве аргументов.
- В вашем AJAX-файле вызовите функцию, используя официальное событие DOM (onclick, onfocus, onblur, onload и т. Д.). В зависимости от того, какие другие элементы содержатся в вашем ответе, вы можете быть достаточно умными, чтобы заставить его чувствовать себя без шва. Передайте ваши динамические элементы в качестве аргументов.
- Когда ваш элемент ответа заполняется и событие происходит, функция запускается.
Пример
В этом примере я хочу прикрепить динамический список автозаполнения из библиотеки jquery-ui к элементу AJAX ПОСЛЕ добавления элемента на страницу. Легко, правда?
start.php
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<!-- these libraries are for the autocomplete() function -->
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/ui-lightness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
<!--
// this is the ajax call
function editDemoText(ElementID,initialValue) {
try { ajaxRequest = new XMLHttpRequest();
} catch (e) {
try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try { ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}}}
ajaxRequest.onreadystatechange = function() {
if ( ajaxRequest.readyState == 4 ) {
var ajaxDisplay = document.getElementById('responseDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?ElementID="+ElementID+"&initialValue="+initialValue;
ajaxRequest.open("GET", "ajaxRequest.php"+queryString, true);
ajaxRequest.send(null);
}
// this is the function we wanted to call in AJAX,
// but we put it here instead with an argument (ElementID)
function AttachAutocomplete(ElementID) {
// this list is static, but can easily be pulled in from
// a database using PHP. That would look something like this:
/*
* $list = "";
* $r = mysqli_query($mysqli_link, "SELECT element FROM table");
* while ( $row = mysqli_fetch_array($r) ) {
* $list .= "\".str_replace('"','\"',$row['element'])."\",";
* }
* $list = rtrim($list,",");
*/
var availableIDs = ["Demo1","Demo2","Demo3","Demo4"];
$("#"+ElementID).autocomplete({ source: availableIDs });
}
//-->
</script>
</head>
<body>
<!-- this is where the AJAX response sneaks in after DOM is loaded -->
<!-- we're using an onclick event to trigger the initial AJAX call -->
<div id="responseDiv"><a href="javascript:void(0);" onclick="editDemoText('EditableText','I am editable!');">I am editable!</a></div>
</body>
</html>
ajaxRequest.php
<?php
// for this application, onfocus works well because we wouldn't really
// need the autocomplete populated until the user begins typing
echo "<input type=\"text\" id=\"".$_GET['ElementID']."\" onfocus=\"AttachAutocomplete('".$_GET['ElementID']."');\" value=\"".$_GET['initialValue']."\" />\n";
?>