[英]jQuery and Ajax Loading Images
我有一個擁有大量高分辨率圖像的龐大投資組合的網站。
我不想調整這些圖像的大小,但是我希望能夠異步拉它們。
出現jQuery .ajax
但是我的代碼有某種錯誤。 它的作用似乎是插入頁面,而不是圖像“ src”
你能幫我嗎:
// Load in the images via ajax:
var $imgs = $('.ajax-image');
$imgs.each(function(i){
var $imgsrc = $(this).attr('src');
var $url = '/php/pull-image.php?i=' + $imgsrc;
$.ajax({
url : $url,
mimeType: "text/plain",
processData : false,
cache: false,
success: function (html) {
$(this).attr('src', html);
}
});
});
和PHP:
$path = $_GET['i'];
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
echo 'data:image/' . $type . ';base64,' . base64_encode($data);
圖像標簽很簡單: <img src="http://example.com/images/image.ext" />
我在這里做錯了什么? 以及如何解決?
您的php頁面出現錯誤,因為您沒有為參數i
傳遞任何內容。 因此,您的php會引發404
錯誤-完整的HTML響應。
我認為您遇到了導致這種錯誤的JavaScript語法錯誤:
url : '/php/pull-image.php?i=' . $imgsrc,
將此行替換為:
url : '/php/pull-image.php?i=' + '<?php echo json_encode($imgsrc); ?>' ,
正如我在我的評論中提到的,我不認為這會怎么做你想要什么,但解決當前的問題:這可能是造成因為this
在的情況下success
的功能,是不一樣的this
在您的each()
函數的上下文。
您應該保存元素,以便可以在success
函數中訪問它:
$imgs.each(function(i){
var el = $(this),
$imgsrc = el.attr('src'),
$url = '/php/pull-image.php?i=' + $imgsrc;
$.ajax({
url : $url,
mimeType: "text/plain",
processData : false,
cache: false,
success: function (html) {
el.attr('src', html);
}
});
});
編輯:這里沒有真正需要使用ajax / php來設置圖像的來源。 您還可以使用javascript(分批)生成一些圖像,為圖像添加onload()
函數,並在加載html元素時設置它們的來源,然后獲取下一批。 例如,請參見以下問題: JavaScript:從javascript加載圖像,然后等待該圖像的“加載”事件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.