[英]how to get the id of an img tag in php variable when an image is clicked?
<a href="#"><img src="images/jbl.png" id="idhims"/></a>
<a href="#"><img src="images/swastik.png" id="idhims2" name="img2name"/></a>
單擊以上任一圖像時,我想使用單擊的圖像ID從另一個div
的mysql
數據庫中檢索數據。
我想在SELECT
-Query中使用單擊圖像的ID從mysql數據庫中檢索數據。
使用jQuery
包括在
<script src="http://code.jquery.com/jquery-latest.js"></script>
和
$(document).ready(function(){
$('a').click(function(){
var imgId = $(this).children('img').attr('id');// store the id to varialbe imgId
//alert(imgId);
$.ajax({
type: "POST",
url: "process_form.php",
data: {imageid:imgId},
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
$("#message_ajax").html(data.frmdb);// message_ajax is the id of the container to show the returned value
}
});
});
})
您可以通過$_POST['imageid']
來訪問php頁面中的值
樣本php頁面,它將返回被點擊的圖像的值返回給我們的用戶
$return_arr = array();
$return_arr['frmdb'] = $_POST['imageid'];
echo json_encode($return_arr);
添加函數onclick =“ yourFunction(this.id)”,例如:
<script>
function yourFunction(id) {
alert(id);
}
</script>
對於您的查詢,我使jsfiddle看起來如下
HTML
<img src="http://google.com/img" id="id"/>
<img src="http://google.com/img" id="id1"/>
<img src="http://google.com/img" id="id2"/>
JS
$("img").click(function() {
alert(this.id);
});
將一個動作放入控制器以從DB檢索數據。 就像是
public function actionQuery($id)
{
$result=(your query using $id);
echo CJSON::encode(array('data'=>$result));
}
在頁面上使用jQuery
<a href="#"><img src="1" id="idhims" onclick="query(this)"/></a>
<script type="text/javascript">
function query(obj) {
$.get("your_controller/query", { id: $(obj).attr('id') })
.done(function(data) {
use the data to fill your div;
});
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.