programing

브라우저를 프로그래밍 방식으로 새로 고치려면 어떻게 해야 합니까?

goodjava 2023. 2. 15. 22:02

브라우저를 프로그래밍 방식으로 새로 고치려면 어떻게 해야 합니까?

있어요.Server,Client ★★★★★★★★★★★★★★★★★」Viewer이치노 워크플로우

  1. ' ' 의 Client Server을 사용하다
  2. 사용자는 php 스크립트를 통해 이미지를 업로드합니다.
  3. 이미지는 html에 포함되어 있습니다.
  4. Viewer이치키보드를 사용할 수 없습니다.Viewer는 항상 웹 브라우저를 실행하여 그림 페이지를 표시합니다.

현재 문제는 서버 디스크의 사진이 변경되어도 웹 페이지가 업데이트되지 않는다는 것입니다.뷰어 또는 웹 페이지의 일부에서 웹 브라우저를 새로 고치려면 어떻게 해야 합니까?

저는 html, css, javascript, php, ajax를 알고 있습니다만, 충분히 알고 있지 않은 것 같습니다.

이를 실현하는 방법에는 적어도 세 가지가 있습니다.

순수 HTML

Amitd의 코멘트에서 지적된 바와 같이 "show.html"에 다음 내용을 추가합니다.<meta>「」에 를 붙입니다.<head>★★★★

<meta http-equiv="refresh" content="5" />

그러면 5초마다 페이지가 자동으로 새로 고쳐집니다.을 합니다.content원하는 초수에 기인합니다.

순수 JavaScript:

미노모어가 지적했듯이document.location.reload()이치노

<script type="text/javascript">
    //put this somewhere in "show.html"
    //using window onload event to run function
    //so function runs after all content has been loaded.
    //After refresh this entire script will run again.
    window.onload = function () {
        'use strict';
        var millisecondsBeforeRefresh = 5000; //Adjust time here
        window.setTimeout(function () {
            //refresh the entire document
            document.location.reload();
        }, millisecondsBeforeRefresh);
    };
</script>

또한 tpower에서 지적한 바와 같이 AJAX 요청을 사용할 수 있지만 원하는 이미지로 URL을 되돌리려면 웹 서비스를 작성해야 합니다.AJAX 요청을 수행하기 위한 JavaScript는 다음과 같습니다.

<script type="text/javascript">
    //put this somewhere in "show.html"
    //using window onload event to run function
    //so function runs after all content has been loaded.
    window.onload = function () {
        'use strict';
        var xhr,
            millisecondsBeforeNewImg = 5000;    // Adjust time here
        if (window.XMLHttpRequest) {
            // Mozilla, Safari, ...
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            // IE
            try {
                // try the newer ActiveXObject
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    // newer failed, try the older one
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    // log error to browser console
                    console.log(e);
                }
            }
        }
        if (!xhr) {
            // log error to browser console
            console.log('Giving up :( Cannot create an XMLHTTP instance');
        }
        xhr.onreadystatechange = function () {
            var img;
            // process the server response
            if (xhr.readyState === 4) {
                // everything is good, the response is received
                if (xhr.status === 200) {
                    // perfect!
                    // assuming the responseText contains the new url to the image...
                    // get the img
                    img = document.getElementById('theImgId');
                    //set the new src
                    img.src = xhr.responseText;
                } else {
                    // there was a problem with the request,
                    // for example the response may contain a 404 (Not Found)
                    // or 500 (Internal Server Error) response code
                    console.log(xhr.status);
                }
            } else {
                // still not ready
                // could do something here, but it's not necessary
                // included strictly for example purposes
            }
        };
        // Using setInterval to run every X milliseconds
        window.setInterval(function () {
            xhr.open('GET', 'http://www.myDomain.com/someServiceToReturnURLtoDesiredImage', true);
            xhr.send(null);
        }, millisecondsBeforeNewImg)
    };
</script>

기타 방법:

마지막으로, 당신의 질문에 tpower의 대답에 답하려면... $.ajax()jQuery를 사용하여 AJAX 콜을 실행합니다.jQuery는 AJAX 콜과 DOM 조작을 훨씬 쉽게 하는 JavaScript 라이브러리입니다.jQuery 라이브러리를 사용하려면 jQuery 라이브러리에 대한 참조를 포함시켜야 합니다.<head>)) ( 로44 1.4.2 ) :

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

또한 "jquery.min.js"를 다운로드하여 로컬로 호스트할 수도 있지만 스크립트가 로드된 URL만 변경됩니다.

위의 AJAX 함수는 jQuery를 사용하여 작성하면 다음과 같습니다.

<script type="text/javascript">
    //put this somewhere in "show.html"
    //document.ready takes the place of window.onload
    $(document).ready(function () {
        'use strict';
        var millisecondsBeforeNewImg = 5000;    // Adjust time here
        window.setInterval(function () {
            $.ajax({
                "url": "http://www.myDomain.com/someServiceToReturnURLtoDesiredImage",
                "error": function (jqXHR, textStatus, errorThrown) {
                    // log error to browser console
                    console.log(textStatus + ': ' + errorThrown);
                },
                "success": function (data, textStatus, jqXHR) {
                    //get the img and assign the new src
                    $('#theImgId').attr('src', data);
                }
            });
        }, millisecondsBeforeNewImg);
    });
</script>

jQuery 버 j j j j j j j j j j j j j j j j j j j j j.그러나 프로젝트의 범위가 작기 때문에 jQuery의 추가 오버헤드를 신경 쓸 필요가 있는지 모르겠습니다(그 정도는 아닙니다).프로젝트 요건에 따라 jQuery가 가능한지 여부도 알 수 없습니다.이를 든 '무엇을 할 것인가'라는에 대한 입니다.$.ajax()

이미지를 갱신할 수 있는 다른 방법도 있을 거라고 생각합니다.개인적으로 이미지 URL이 항상 변경된다면 AJAX 루트를 이용하겠습니다.정적인 「을 사용합니다.<meta>리프레시 태그

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ 쓰세요.WebSockets.

하면 .websocket connection 서버가 요.Viewer업데이트될 때마다요.디스플레이나 사용자 상호 작용을 방해하지 않고 완전히 비동기화된 웹 소켓을 통해 업데이트된 이미지를 전송할 수 있습니다.

타이머를 사용하면 빠른 업데이트를 받을 수 없거나 페이지를 사용하지 않고 계속 새로 고칩니다.


세부사항:

합니다.pywebsocket ★★★★★★★★★★★★★★★★★」phpwebsocket.

클라이언트:

HTML5 웹 소켓 지원이 필요합니다.현재 모든 브라우저가 지원되고 있습니다.

이미지 업데이트 시 메시지를 등록해야 합니다.콜백을 등록하는 것과 같습니다.

예:

wSocket = new WebSocket('ws://' + serverIP + ':' + serverPort + '/images');

wSocket.onopen = function() {
    console.log("Primary Socket Connected.");

    connectedPrimary = true;

    wSocket.send("sendImageUpdates");
};

wSocket.onmessage = function(evt) {
    // evt is the message from server

    // image will be representated as a 64 encoded string

    // change image with new one
    $("#image").attr('src', 'data:image/png;base64,' + evt.data);
}

wSocket.onclose = function() {
    console.log("Primary Socket Closed.");

    wSocket = null;
};

wSocket.onerror = function(evt) {
    alert(evt);
}

는 「」에 .wSocket.onmessage호출될 거고, 그걸로 필요한 건 뭐든지 할 수 있어요

서버:

클라이언트로부터의 접속을 수신합니다(복수의 클라이언트를 서포트하도록 설정할 수 있습니다). " " " " " " " 가 되면"sendImageUpdates"이 수신되면, 서버는 이미지내의 갱신을 기다립니다.새 이미지가 업로드되면 서버는 새 메시지를 생성하여 클라이언트에 보냅니다.

장점

  1. 이미지가 업로드되는 즉시 및 이미지가 업로드될 때만 업데이트를 받습니다.
  2. 클라이언트는 이미지가 변경되었음을 인식하고 추가 기능을 수행할 수 있습니다.
  3. 완전 비동기화 및 서버 구동형

AJAX 요청을 사용하여 도움을 받을 수 있습니다.예를 들어 5초마다 서버에서 이미지를 폴링합니다.대신 서버에서 새 이미지 ID를 폴링하고 이미지 원본에 난수 대신 해당 ID를 사용할 수 있습니다.이 경우 새 이미지가 있을 때만 src 속성이 변경/새로고침됩니다.

<script language="JavaScript"><!--
function refreshIt() {
   if (!document.images) return;
   $.ajax({
      url: 'latest-image-id.json',
      success: function(newId){
          document.images['doc'].src = 'doc.png?' + newId;        
      }
   });
   setTimeout(refreshIt, 5000); // refresh every 5 secs
}
//--></script>
</head>
<body onLoad=" setTimeout(refreshIt, 5000)">
<img src="doc.png" name="doc">

또는 웹 소켓을 통해 이미지가 변경되었을 때 서버에서 알림을 받는 방법도 있습니다.

특정 시간 간격으로 페이지를 새로고침하면 문제가 발생할 수 있습니다.

setTimeout(function(){
window.location.reload(1);
}, 5000);

위의 코드는 5초 후에 현재 페이지를 새로고침합니다.

또는

또, 어시스턴스 콜을 선택해, 페이지 전체를 갱신할 필요도 없습니다.다음 코드를 확인합니다.

$.ajax({
  url: "test.aspx",
  context: document.body
}).done(function() {
  $(this).addClass("done");
});

이것은, 의 인스톨로 사용할 수 있습니다.window.location.reload(1);

[**test.disc:*]* 이 페이지는 로드 시 모든 이미지 src, 즉 이미지를 페이지로 가져오는 서비스를 가져와야 합니다.]

이렇게 하면 다음과 같은 결과를 얻을 수 있습니다.data에서done(function()현재 페이지의 html 요소에 할당할 수 있습니다.예:

done(function() {
$('#ImageId').attr('src', data);
 });

그러면 img 태그의 src가 다음과 같이 설정됩니다.datatest.aspx에서

장점:페이지 전체가 새로 고쳐지지 않고 새 이미지만 추가됩니다.

jQuery Ajax에 대한 자세한 내용은 이 링크를 참조하십시오.

사용하다.

document.location.reload();

예를 들어 버튼을 클릭하는 경우:

<input type="button" value="Reload Page" onClick="window.location.reload()">

COME이라고 불리는 서버와의 클라이언트 롱 폴링 접속을 실장하거나 브라우저에서 웹 소켓을 지원하는 경우 소켓을 사용해야 합니다.

javascript에서는 프로그래밍 방식으로 새로 고치는 몇 가지 방법이 있습니다.

권장되는 방법은 다음과 같습니다.location.reload()

또 다른 방법으로는,location.href브라우저가 자동으로 새 URL로 이동하기 때문에location=location또는location.href=location.href그럴 수도 있어요.

두 번째 방법은 이상하게 보일 수 있지만요.

요약하면 다음과 같습니다.

location.reload();
//or
location.href=location.href;
//or
location=location;


I hope this helped.

가장 쉬운 것은 AJAX 풀링을 사용하는 것입니다.
업로드를 처리하는 php 파일의 경우 새 사진이 업로드되면 unix 타임스탬프를 파일에 저장합니다.

file_put_contents('lastupload.txt', strval(time())); // Save timestamp of upload

AJAX 콜을 처리하는 다른 php 파일(예: polling.php)을 생성하여 마지막 업로드의 unix 타임스탬프를 반환합니다.

echo file_get_contents('lastupload.txt'); // Send last upload timestamp

Viewer javascript 코드에서 타임스탬프의 변화를 감지하고 필요할 때 이미지를 새로 고치는 AJAX 폴링을 수행합니다.

$(function() {
   setInterval(polling, 1000); // Call polling every second.
});
var lastupload = 0;
function polling() {
   $.ajax({
      url: 'polling.php',
      success: function(timestamp){
          if (timestamp > lastupload) { // Is timestamp newer?
              document.images['image'].src = 'image.png?' + timestamp; // Refresh image
              lastupload = timestamp;
          }
      }
   });
}

코드를 테스트하지 않았기 때문에 오류가 있을 수 있지만, 이것이 아이디어입니다.

그렇게 많은 스크립트가 필요하지 않다고 생각합니다.이미지 URL 바로 뒤에 물음표와 난수만 추가하면 그 문제를 해결했습니다.이미지 URL을 변경하지 않으면 브라우저가 캐시에서 호출합니다.

페이지에 최신 사진을 표시하려면:

<img src="<?php echo $image_url; ?>?<?php echo rand(10,99); ?>"/>

다음과 같이 인쇄됩니다.

http://static.example.com/myimage.jpg?56 

당신의 질문과 나의 해결책은 나의 문제에서 Jquery와 javascript 난수 함수를 사용하여 이미지 URL을 난수로 변경함으로써 이미지 URL을 새로 고치는 것입니다.요점을 파악하셨고 필요에 맞게 조정해 주셨을 겁니다.

$('#crop_image').live('click',function(){
    $(this).html(ajax_load_fb);
    var x = $('#x').val();
    var y = $('#y').val();
    var w = $('#w').val();
    var h = $('#h').val();
    var dataString = 'process=image_crop&x='+x+'&y='+y+'&w='+w+'&h='+h;
    $.ajax({
        type: 'POST',
        url: '<?php echo $siteMain;?>ajax/ajaxupload.php',
        data: dataString,
        cache: false,
        success: function(msg) {
            $('#crop_image').html('Crop Selection');
            $('.crop_success_msg').slideDown('slow');
            var numRand = Math.floor(Math.random()*101);
            $('#current_img').html('<img src="/images/large_<?php echo $user['username'];?>.jpg?'+numRand+'"/>');
        },
        error: function(response, status, error)
        { 
            $(this).html('Try Again');
        }
    });
});

뷰어 웹 브라우저에 작은 php 스크립트를 작성하여 이미지를 정기적으로 확인하고 변경 시 새로고침하는 것이 가장 좋습니다.php 코드는 서버 측에서 실행되므로 쉽게 실행할 수 있습니다.코드 스니펫이 필요하시면 알려주세요.

언급URL : https://stackoverflow.com/questions/13376048/how-do-i-programmatically-refresh-a-browser