我正在使用 PHP 脚本生成一些包含 javascript 的 HTML(来自 jQuery UI 的 DatePicker)。
使用 jQuery/AJAX 从主页调用 PHP 脚本。我的所有 HTML 渲染都没有问题,但我收到一个控制台错误:
未捕获类型错误:$(...).datepicker 不是函数
我显然做错了什么,但我并不是一个 Javascript 专家。如果我直接调用 new-fields.php ,代码可以正常工作,但是当我通过 jQuery 获取它时,代码就会崩溃。感谢任何帮助!
Main.html:
<script type="text/javascript">
jQuery('input[name="location"]').click(function(){
var data = {location : jQuery(this).val(), department : $('input[name="department"]:checked').val()};
jQuery.ajax({
url: "/new-fields.php",
type:'POST',
data: data,
dataType: 'text',
success: function(result){
jQuery('#div-custom').html(result).show();
$("#div-custom").find("script").each(function() {
eval($(this).text());
});
}
});
});
</script>
新字段.php:
$picker = '<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker1" ).datepicker({
numberOfMonths: 3,
showButtonPanel: true
});
});
</script>
<script>
$(function() {
$( "#datepicker2" ).datepicker({
numberOfMonths: 3,
showButtonPanel: true
});
});
</script>
<p>Date: <input type="text" id="datepicker1"></p>
<p>Date: <input type="text" id="datepicker2"></p>';
echo $picker;
最佳答案
您收到错误,因为在您的主文档中您使用 jQuery
,我假设出于不冲突的目的,在success
中您同时使用 jQuery
的处理程序和$
最后在 ajax
您再次使用 $
的响应符号。
我的方法是将 javascript 移出 ajax
回应。
加载所有.js
文件到你的主文档中,取出所有 <script>
响应中的引用并丢失 eval
.
更改 ajax
success
像这样的处理程序
success: function(result){
jQuery('#div-custom').html(result).show();
jQuery("#div-custom").find("#datepicker1,#datepicker2" ).datepicker({
numberOfMonths: 3,
showButtonPanel: true
});
}
还有你的php
文件应该是:
$picker = '<p>Date: <input type="text" id="datepicker1"></p>
<p>Date: <input type="text" id="datepicker2"></p>';
echo $picker;
关于javascript - AJAX 响应中的 jQuery UI 日期选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246059/