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

I have a couple of different places in my page where I render this to set a variable like this

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

My problem is that I refresh the whole body of the page with ajax, and when I do this piece of code is not executed again. I can't really set an id to the script block since many of these blocks will be looped out and I wouldn't know which one to call eval() on.

Can I somehow append this declaration to a function or object like "myDeclarationObject" and then just call eval() on that object together with the page refresh?

I know I could study up on the nuts and bolts of javascript but I am short on time, there are so many things you need to learn if you develop an app singlehandedly =)

Some more sample code...

<!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>

As you may notice, each div with id slide1, slide2 etc. are looped out according to a certain template. all slides except slide2 are of a template type that don't have this script block I am talking about, however slide2 does, and many more may have it.

Is there a good way of putting this data in, instead of rendering a scriptblock like I do here?

At the time I initialize the array videoContent and declare it with null values the page is not yet aware that it will populate number2 of the array with this value.

Here is the slideshow and ajaxUpdate scripts:

/* 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 is a symfony2 app.

查看全部
duanseci1039
duanseci1039
2012/11/05 09:05
  • php
  • symfony
  • ajax
  • javascript
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复