这是一个独立的例子。运行后,请注意以下几点:
<head>
在标签中加载 jQuery/jQueryUI 库
- 识别点击了哪张图片:(1) 每当点击类的元素时触发点击事件
img
,(2) 通过 jQuery 获取特定的 img 的 ID
- 使用 AJAX 将该图像 ID 发送到 PHP 处理器文件
- PHP 处理器文件做一些事情,并返回一个结果
- 在 AJAX 成功函数中收到的来自 PHP 的结果。使用接收到的数据(来自 PHP)的所有处理必须在成功函数内进行,包括调用 JQUI dlg
- JQUI dlg 以 TEST.PHP 中的空 DIV 开头,在 AJAX 成功函数中填充了标记:
$('#dlgID').html(data_received_from_PHP);
- 请记住在单击 OK 按钮时关闭 JQUI dlg(否则您可以将该命令放在
close:
JQUI dlg 的部分中)
要运行这个简单的示例,您将需要两个文件:
文件 1:TEST.PHP
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
$(document).ready(function() {
$('.img').click(function() {
var iid = $(this).attr('id');
//alert('You clicked ID: ' + iid);
$.ajax({
type: "POST",
url: "yogibear.php", // "source.php",
data: "iid="+iid,
success: function(data) {
//alert('AJAX recd: ' +data);
$('#moddlg').html(data);
$('#moddlg').dialog('open');
} //END success fn
}); //END $.ajax
});
$('#moddlg').dialog({
autoOpen: false,
modal: true,
width: 400, //default is 300
title: 'This is yer dialog:',
buttons: {
'Click Me': function() {
$(this).dialog('close');
}
},
close: function() {
alert('Dlg is closing... I can do more stuff in here, including running another AJAX call');
}
});
}); //END $(document).ready()
</script>
</head>
<body>
<img id="i-1" class="img" src="http://placehold.it/140x100" />
<img id="i-2" class="img" src="http://placehold.it/140x100" />
<img id="i-3" class="img" src="http://placehold.it/140x100" />
<img id="i-4" class="img" src="http://placehold.it/140x100" />
<div id="moddlg"></div>
</body>
</html>
文件 2:YOGIBEAR.PHP
<?php
$x = $_POST['iid'];
die('PHP file recd: ' . $x);
//Of course, this is where you receive the img id sent via AJAX
//and look up stuff in MySQL or etc, then return the results
//simply by putting it all into a variable and ECHOing that
//variable. Or, you can use JSON to echo an array - but make
//sure to look up a couple of examples as you must add another
//couple of params to the AJAX code block