如何在ajax页面刷新上声明变量

时间:2012-11-05 09:05:12

标签: php javascript ajax symfony slideshow

我的页面中有几个不同的位置,我将其渲染为设置这样的变量

<script>
videoContent[{{ ordernumber }}]='video={{ c.data[0] }}&height={{ c.data[1] }}&width={{ c.data[2] }}&codec={{ c.data[3] }}&fullscreen={{ data5 }}';
</script>

我的问题是我用ajax刷新了整个页面,当我这样做时,这段代码不再被执行了。我不能真正为脚本块设置一个id,因为很多这些块都会被循环出来,我不知道哪个块可以调用eval()。

我可以以某种方式将此声明附加到像“myDeclarationObject”这样的函数或对象,然后只需在页面刷新时调用该对象上的eval()吗?

我知道我可以研究javascript的细节但是我的时间很短,如果你单独开发一个应用程序,你需要学习很多东西=)

更多示例代码......

<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>
<head>
  <title>$title</title>
  <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
  <script src="/symfony/web/script/jquery-1.8.2.min.js" type='text/javascript'></script>
  <script src="/symfony/web/script/slideshow.js" type='text/javascript'></script>
  <script type='text/javascript'>
  /* set globals */
  var newContent = 'blank';
  var currentUri = '/symfony/web/app.php/Screen/showContainer/39';
  /* fire the slideshow from slide 1 once document is finished loading */
  $(document).ready(function(){
    console.log('start of slideshow');
    slideshow(1);
  </script>
</head>
<body id="slideshow_body">
  <script id='pauseTimesScript' type='text/javascript'>
  /* initialize the array to keep track of which slides have videocontent */
  try {
        videoContent=null;
        videoContent=undefined;
        videoContent = new Array();         
        /*alert('satte först till null, deklarerade sedan om.');*/
  } catch(e) {
        videoContent = new Array();         
        /*alert('deklarerade utan att först sätta null.');*/
  }
  /* Define pauseTimes (array holding duration of each slide) */
  try {
        pauseTimes=null;
        pauseTimes=undefined;
        pauseTimes = new Array();   
        setPauseTimes();        
        /*alert('satte först till null, deklarerade sedan om.');*/
  } catch(e) {
        pauseTimes = new Array();   
        setPauseTimes();        
        /*alert('deklarerade utan att först sätta null.');*/
  }
  /* This function sets pausetimes as well as initializes the array for videocontent */
  function setPauseTimes() {  
    pauseTimes[1]=2000;
    videoContent[1]=null;
    pauseTimes[2]=15000;
    videoContent[2]=null;
    pauseTimes[3]=2000;
    videoContent[3]=null;
    pauseTimes[4]=2000;
    videoContent[4]=null;
    pauseTimes[5]=1000;
    videoContent[5]=null;
    pauseTimes[6]=0;
    videoContent[6]=null;
  }
  </script>
  <div id="avbrott">
    Tillfälligt avbrott, visar cachelagrat innehåll sedan 2012-11-05 10:23:31
  </div>
  <div id="canvas">
    <div class="slide" id="slide1">
      <div id="slide_bg">
      <div id="preview_title">
        Egypt rocks!
        </div>
        <div></div>
        <p id="preview_data_6">Lorem ipsum
        dolor sit amet, consectetur adipiscing elit. Suspendisse feugiat
        pharetra eros, vitae ullamcorper tellus condimentum sit amet.
        Pellentesque habitant morbi tristique senectus et netus et malesuada
        fames ac turpis egestas. Suspendisse in leo erat. Aliquam interdum
        molestie tortor, nec lacinia mauris viverra eget. Suspendisse aliquam
        tempor scelerisque. Proin vel purus nunc. Pellentesque ut sapien
        libero.<br /></p>
      </div>
    </div>
    <div class="slide" id="slide2">
      <div id="slide_bg">
      <img src="/symfony/web/style/images/ajax-loader3.gif"  /></div>
      <div id="no_preview_text"></div>
            <script id="videoContentScript2">
      videoContent[2]='video=video.avi&height=800&width=600&codec=h264&fullscreen=0';
      </script>
    </div>
    <div class="slide" id="slide3">
      <div id="slide_bg">
      <div id="preview_title">
        info
        </div>
        <div></div>
        <p id="preview_data_6">In ornare
        fringilla convallis. In cursus pellentesque elit a iaculis. Fusce
        rutrum rutrum neque quis molestie. Fusce id lacus in est iaculis
        eleifend venenatis eget ante. Sed eget augue sed nisl scelerisque
        fermentum eget at arcu. Donec placerat turpis non sapien scelerisque
        tempus. Etiam imperdiet urna sit amet nulla convallis a facilisis dui
        scelerisque. Ut sed eros a velit venenatis lacinia ut id risus. Duis
        aliquam augue in erat malesuada ut eleifend justo condimentum. Praesent
        quis urna nisl. Vestibulum suscipit tincidunt nisl id tincidunt. Nunc
        ac ante sed lectus scelerisque blandit. Fusce ultrices, nulla nec
        porttitor dapibus, tellus libero fringilla odio, semper tincidunt
        mauris velit eu augue. Duis ut massa sed nibh auctor malesuada id eget
        ipsum.</p>
      </div>
    </div>
    <div class="slide" id="slide4">
      <div id="slide_bg">
      <div id="preview_title">
        Lite lek
        </div>
        <div></div>
        <p id="preview_data_6">Morbi ac
        rhoncus velit. Nunc blandit urna eu mi tempus volutpat. Quisque vel
        eros tortor. Sed fringilla, magna sit amet luctus imperdiet, urna
        libero dapibus nulla, in facilisis sapien ante nec ipsum. Maecenas
        suscipit orci nec turpis iaculis porttitor. Proin blandit tortor a
        magna porttitor malesuada. Sed porta quam sodales est sollicitudin
        vitae mattis quam consequat. Cum sociis natoque penatibus et magnis dis
        parturient montes, nascetur ridiculus mus. Ut eget accumsan ligula.
        Fusce a urna in diam sollicitudin ullamcorper. Donec et tellus quis
        justo scelerisque fermentum. Nunc molestie malesuada odio laoreet
        fermentum. Proin vel vestibulum nunc. Aliquam odio sem, elementum vel
        bibendum sit amet, ullamcorper quis tortor. Donec tempus massa
        pellentesque metus ornare eget laoreet enim porta. Nullam facilisis
        tempus neque vitae bibendum.</p>
      </div>
    </div>
    <div class="slide" id="slide5">
      <div id="slide_bg">
      <div id="preview_title">
        Feel the rythm
        </div>
        <div></div>
        <p id="preview_data_6"><br />
        <br />
        <br />
        <br />
        The rythm of the night =p</p>
      </div>
    </div>
    <div class="slide" id="slide6">
      <div id="slide_bg">
      <div id="preview_title">
        skipme
        </div>
        <div></div>
        <p id="preview_data_6">skipme</p>
      </div>
    </div>
  </div>
</body>
</html>

正如您所注意到的,每个具有id slide1,slide2等的div都会根据某个模板循环显示。除了slide2之外的所有幻灯片都是一个模板类型,我没有讨论这个脚本块,不过有滑块2可以使用,还有更多可以使用它。

有没有一种很好的方式来放入这些数据,而不是像我这样渲染一个脚本块?

当我初始化数组videoContent并使用null值声明它时,页面还不知道它将使用此值填充数组的number2。

以下是幻灯片演示和ajaxUpdate脚本:

/* The actual slideshow function (calling itself for each new slide) */
function slideshow(slide) {

    if(pauseTimes[slide]==null) {
        console.log('no slide defined, so update the whole thing');
        ajaxUpdate();
    }
    else if (pauseTimes[slide]==0) {
        console.log('pauseTime is zero so move to next slide');
        slideshow(slide+1);
    }
    else if (pauseTimes[slide]>0) {
        /* if there is another slide after the one currently showing... */
        skip=0; //wheather to skip this slide
        //check for video stuff
        if(videoContent[slide] != null) {

            if (parent.xPos) {
                myXpos = Math.round(parent.xPos)
            }
            else {
                myXpos = 0;
            }

            if (parent.yPos) {
                myYpos = Math.round(parent.yPos)
            }
            else {
                myYpos = 0;
            }           

            //These position variables are set by a script in screen_base.html.twig
            positionString = '&x=' + myXpos + '&y=' + myYpos;

            //the videoContent[slide] is populated from the template for the video slide
            videoCallstring = 'http://127.0.0.1/index.php?' + videoContent[slide] + positionString;

            //call by ajax:
            window.skip=1;
            jQuery.ajax({
                 url:    videoCallstring,
                 success: function(result) {
                        window.skip=1;
                             /*
                              if(result.isOk == false) {
                                  alert(result.message);
                              }
                              else {
                                  alert("success =)");
                              }
                              * */
                        },
                 async:   false
            });             
        }
        else {
            //do nothing
        }       

        if (skip == 1) {
            slideshow(slide+1);
        }
        else {
            $('#slide'+slide).
            fadeIn(1500,function(){}).
            delay(pauseTimes[slide]).
            fadeOut(1500,function(){slideshow(slide+1);});
        }
    }
}

    /* The update routine at the end of each slideshow */
function ajaxUpdate() {

    //Load current uri again asynchroneously

    var jqxhr = $.get(currentUri)
      .success(function(data) {

            newContent = data; 

            //make sure we got the end token (</body>) so that our transmission wasn't interrupted in the middle of the request
            endtoken_test = newContent.search('</body>');

            //strip of everything before starttoken (<body>)
            newContent = newContent.substring(newContent.indexOf('<body id="slideshow_body">') +26 );

            //strip of everything after endtoken (</body>)
            newContent = newContent.slice(0, newContent.lastIndexOf("</body>"));

            if (endtoken_test != -1) {
                //We found the endtoken which means the whole page was returned

                //replace the innerHTML of body with the new stuff
                document.getElementById('slideshow_body').innerHTML=newContent;

                //Ta bort skylten om tillfälligt avbrott (om den visades)
                document.getElementById('avbrott').style.display = 'none';

                //update the pausetimes
                ie_compatible_eval(document.getElementById('pauseTimesScript').innerHTML)

                //update the videoContents
                /* Loop out the scriptblocks in a try/catch way, loop until max number in pauseTimes is reached */


                //run the slideshow anew
                slideshow(1);
            }
            else {      
                /* if no content (or at least not all of it) could not be downloaded from server */
                document.getElementById('avbrott').style.display = 'block';
                slideshow(1);
            }

      })
      .error(function() {

            newContent = 'blank'; 

            /* if no content (or at least not all of it) could not be downloaded from server */
            document.getElementById('avbrott').style.display = 'block';
            slideshow(1);

      });   

}



/* eval() som även funkar i explorer, används för att uppdatera paustiderna */

function ie_compatible_eval(code) {
    var dj_global = this; // global scope reference

    if (window.execScript) {
        window.execScript(code); // eval in global scope for IE
        return null; // execScript doesn’t return anything
    }

    return dj_global.eval ? dj_global.eval(code) : eval(code); //eval för andra browsers
}

Servreside是一个symfony2应用程序。

1 个答案:

答案 0 :(得分:0)

我的幻灯片中有几张不同的幻灯片,我将其渲染为设置这样的变量

<script>
//define the function for later use (page updates)
function videoContentUpdate1() {    
    videoContent[1]='video={{ data0 }}&height={{ data1 }}&width={{ data2 }}&codec={{ data3 }}&fullscreen={{ data5 }}';
}
//run it the first time (later on this will not run it by itself, we have to call the function specifically.
videoContentUpdate1();
</script>

当我的页面使用ajax刷新时,我会使用此代码,以便每次刷新整个页面(幻灯片)时重新运行videoContentUpdateX():

            //update the videoContents
            for (var i=1;i<(pauseTimes.length+1);i++)
            { 
                try {
                    var x = window['videoContentUpdate'+i];
                    x();
                }
                catch(e) {
                    //do nothing since we will not have a function named that for every slide, error is expected
                }
            }

我不知道这是否是一种很好的方法,但它工作正常=)