Saturday, June 13, 2009

Обновление картинки без перезагрузки HTML страницы

Постановка задачи:
Картинка на странице подгружается с php скрипта.
Допустим пользователь изменил картинку которая хранится на сервере (например зааплодил новую с помощmю плагина Uploadify), нужно теперь без перезагрузки страницы обновить картинку с того самого php скрипта.

Похожие задачи:
При создании простенькой галереи, когда пользователь аплодит картинку и нужно эту картинку отобразить, или например при создании скрипта каптчи, или когда пользователь меняет логотип в своем профайле и т. д.

Так вот, приведу пример refresh картинки на jquery

код примерно такой:

<div id="img_container">
<img src="http://site.com/img.php?img_id=1" />
</div>

<input type="button" onclick="refresh_my_img();">

<script type="text/javascript">
function refresh_my_img()
{
time = new Date();
var rand = time.getTime();
var new_src = "http://site.com/img.php?img_id=1"+"&add_param="+rand;
$("#business_logo_img").empty();
var i = new Image();
i.src = new_src;
$("#business_logo_img").append(i);
}
</script>

В данном случае, удаляется тег img и создается новый с другим src.
ОСОБОЕ ВНИМАНИЕ хочу обратить на новый ресурс картинки, в url адрес добавился новый параметр add_param=rand где rand типа случайное уникальное число.
Это сделано для того, чтобы браузер не считал что адрес картинки старый.
Если бы мы для картинки просто подставили бы старый url (url того же php скрипта, который был до этого), то браузер посчитал бы что картинка старая, и не обновил бы её, а так, с помощью левого параметра, мы просто подставляем картинке уникальный новый url, это заставит браузер послать запрос на php скрипт, который в свою очередь вернет нам новую картинку. В самом же скрипте новый параметр обрабатывать не нужно.

Эта статья полезна для тех случаев, когда картинка возвращается php скриптом. (Не забывайте, что скрипт при выводе картинки должен выводить необходимые headers)

1 comment:

  1. Your car might be stolen if you don't keep this in mind!

    Consider that your car was taken! When you visit the police, they inquire about a specific "VIN decoder"

    A VIN decoder: What is it?

    Similar to a passport, the "VIN decoder" allows you to find out the date of the car's birth and the identity of its "parent"( manufacturing plant). You can also figure out:

    1.Type of engine

    2.Model of a car

    3.The DMV's limitations

    4.The number of drivers in this vehicle

    You'll be able to locate the car, and keeping in mind the code ensures your safety. The code can be viewed in the online database. The VIN is situated on various parts of the car to make it harder for thieves to steal, such as the first person's seat on the floor, the frame (often in trucks and SUVs), the spar, and other areas.

    What happens if the VIN is intentionally harmed?

    There are numerous circumstances that can result in VIN damage, but failing to have one will have unpleasant repercussions because it is illegal to intentionally harm a VIN in order to avoid going to jail or the police. You could receive a fine of up to 80,000 rubles and spend two years in jail. You might be held up on the road by a teacher.

    Conclusion.

    The VIN decoder may help to save your car from theft. But where can you check the car reality? This is why we exist– VIN decoders!

    ReplyDelete