开发者

why doesnt this Javascript work when mixed with php?

开发者 https://www.devze.com 2023-03-05 13:49 出处:网络
im trying to grab search items from twitter via PHP curl, process and update them every second. In this simple version im just trying to refresh the search results for \"bieber\" every second. i have

im trying to grab search items from twitter via PHP curl, process and update them every second. In this simple version im just trying to refresh the search results for "bieber" every second. i have combined php with the javascript and im guessing its the reason things don't work...but I need to understand why. In my understanding Apache sends only html back to the browser...so why is there a problem with the innerHTML specification: Here's the script

<head>
<script type = 'text/javascript'>


function refresh(){
document.getElementById('target').innerHTML= <?

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://search.twitter.com/search.json?q=bieber&rpp=100');

curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

$var = curl_exec($ch);


curl_close($ch);

$obj = json_decode($var, true);



for($i = 0; $i<500; $i++){
if(empty($obj['results'][$i]['text'])){
 echo $i;
 break;
    }
echo $obj['results'][$i]['text']."<br/>";
}

?>
;
var refresher = setTimeout("refresh()",1000);

}

</script>
</head>

<body onLoad="refresh()">
<div>
<span> stuff </span>
<div id ='target'>
</div>


<div id= 'rest'>
The Rest of the page that does not refresh
</div>
</div>
</body>

</html>开发者_如何学Python;

I know there's AJAX and JQuery etc but let's mention them only after we've explained to me why there's a problem with this code and why what im doing is not possible without those technologies.

Thanks!


Take a look at your HTML source that is returned to the browser after the PHP executes on the server side:

<head>
<script type = 'text/javascript'>


function refresh(){
document.getElementById('topTen').innerHTML= Never sewn my daughters as mesmerized as right now while they watch the Justin Bieber movie....sheeeeesh<br/>I just took &quot;A 12 year old and 16 year old co...&quot; and got: 4: We shouldn't, we couldn't, we wouldn't...We did.! Try it: http://bit.ly/mksZGq<br/>@justinbieber +..., is not knowing all his songs, not being a fan is to have all existing products of Justin Bieber +...<br/>Bieber set to meet Sept 11 victim: Justin Bieber is set to meet a 9/11 victim's daughter after a request from US... http://bit.ly/lbP6w6<br/>@xxoxxSasixxoxx hey how many pics am i limited to for the bieber vídeo? :D hahahaha<br/>@MissCarrusel es todo por culpa de la boda real, Justin Bieber y la Gaga...<br/>Bieber set to meet Sept 11 victim: Justin Bieber is set to meet a 9/11 victim's daughter after a request from US... http://bit.ly/lbP6w6<br/>I just took &quot;Your a popular girl at school and Justin Bieber is a n...&quot; and got: Part 2 &quot;a thousand times yes&quot;! Try it: http://bit.ly/jHROiv<br/>ngga sama sama haters kita kwkw @FyaanaR Jenni belieber ya? RT @arikakautsar: Gara&quot; tautan justin bieber hub ane sama jenni jadi gimana git<br/>ei meninas vi agora o trote de vcs no twitcam adorei dançando o
justin bieber (@LuanaSoeira live on http://twitcam.com/4ve65)<br/>Lol ahahahahahahaha Poppy ?? Bieber ?? Really ?? Lol ai it must be that hair @poppyismyname (TV)5<br/>@0rfeo_ Yehuu açıldı læ :D balkona çıkan justin bieber hayranı gbi olcam. ordan atcam mention bağırarak ama..<br/>Dios mio hasta en la sopa RT @tusabiasque Justin Bieber acapara el 3% de los recursos de todo twitter. http://bit.ly/b2bUX0<br/>RT @evenpro: Para los fanáticos de Justin Bieber, esta es la cuenta del Club de Fans en Venezuela ---&gt; @JBieberVenezla<br/>Describe your perfect date? — Being with Bieber. http://4ms.me/mIbZkr<br/>wtf bieber fans? i won't follow you -_- #GoAway<br/>I find that a side effect of bieber fever is the need to scream a LOT. #itsabelieberthing<br/>RT @evenpro: Para los fanáticos de Justin Bieber, esta es la cuenta del Club de Fans en Venezuela ---&gt; @JBieberVenezla<br/>Untung La Justin Bieber Bole Bole Men Kiss2 Ngan EX Aku
*Jeelluuzz ~ http://fb.me/MqNfHaR4<br/>RT @AlexandreMedina: &quot;Prezado senhor Justin Bieber, informamos que o resutado da análise da mancha vermelha em seu pênis era só baton. Lamentamos a amputação&quot;<br/>RT @tusabiasque: Justin Bieber acapara el 3% de los recursos de todo twitter. http://bit.ly/b2bUX0 /Colaborando con la causa Cc: @walterdva<br/>Bieberohhecknophobia: fear of accidentally listening to a Justin Bieber song and not having the ability to rip your freakin ears off<br/>Watch Justin Bieber's movie and tell me he's not talented. He's overrated as a popstar and underrated as a musician.<br/>I just took &quot;(Part 1-11) &quot;Just Because I'm his sister, Doesn't mean I can't meet him.&quot; (...&quot; and got: Part 7:l! Try it: http://bit.ly/kJcbdI<br/>I like inspiring stories. RT @AmazonVideo...Justin Bieber: Never Say Never available at Amazon Instant Video. http://amzn.to/m4mfdA<br/>@JBIndonesiaa dr bieber<br/>I don't know how I got so obsessed but I love Justin Bieber. http://tumblr.com/xkv2i6zju5<br/>I just took &quot;SEASON ONE: ALL PARTS: The plane crash caused you to be stuck on ...&quot; and got: Part 12-HAWAII!!!!! Try it: http://bit.ly/jwlkWP<br/>RT @justinbieber: its here. #NSNweekend #NeverSayNeverDVD - http://itunes.apple.com/us/movie/justin-bieber-never-say-never/id425624519<br/>Dear Justin Bieber........... NEVER! sincerely, i will never say never.<br/>R E T W E E T if you have a serious case of Bieber Fever, and dont want the cure :) [i auto follow back]<br/>RT @evenpro: Para los fanáticos de Justin Bieber, esta es la cuenta del Club de Fans en Venezuela ---&gt; @JBieberVenezla<br/>Justin Bieber Never Say Never ! :) Watching it all day. &lt;3 IloveyouJustinDrewBieber! (((((:<br/>I just took &quot;Raped by my own brother every single day. What happens wh...&quot; and got: Part 33-Happy anniversary!! Try it: http://bit.ly/kiZco4<br/>I just took &quot;Your a bad teen, you sneak out, and skip school. Y...&quot; and got: Part 6 : Gomez. ( Kinda Rated R )! Try it: http://bit.ly/jTvysb<br/>@vangiemartelle Eh kanina ka pa. hahaha. I texted youuu. :))) Sabi ko you've been BIEBER-fied. haha<br/>OMB . i have bieber fever ! ;) &lt;3<br/>RT @OmgSoEpic_: That awkward moment when you realize Flo Rida is Florida Will. I. Am is William , B.o.B is Bob &amp; Justin Bieber is .....WELL..SEXY (; #OSE<br/>TELL ME WHAT IS HAPPENING TO JUSTIN BIEBER?!?!?!?<br/>Did you guys see DC choreographer @DevinMW &amp; #PhunkPhenomenon last night on #ABDC? It was Bieber night! Clip here: http://on.mtv.com/kdOUjE<br/>RT @RachelKaitlyn: Hahahahahahaha this gay guy goes &quot;omg are you talking about justin bieber...? The only thing good about him is his hair&quot;<br/>I liked a @YouTube video http://youtu.be/kspPE9E1yGM?a Justin Bieber vs. Slipknot - Psychosocial Baby<br/>RT @lyekmh: Come watch @awirafael, Justin Bieber of Malaysia, this Sunday for Sunday Afternoon Jam  at Morning Rocket, Cheras<br/>Congratulation for that news!! RT @GuadalupeHyre32: @gabriel_ysturiz LoooooooL :), that's awesome, Justin Bieber (cont) http://tl.gd/aehlt6<br/>@JBIndonesiaa dr bieber<br/>Nowplaying : justin bieber - one less lonely girl :)<br/>Photo:  http://tumblr.com/xuj2i6z47a<br/>GET LAID NOW!! CLICK HERE: http://ow.ly/3Bjc9 #Sex Miley Cyrus Taylor Swift Kim Kardashian Lady Gaga Justin Bieber<br/>Unwell Bieber tells off airport crowd at Manila departure - Manila Bulletin Error Reported, We are sorry for that !<br/>Send this round to support Justin Bieber . We Love you Justin Bieber ♥♥♥♥♥♥♥♥♥♥♥… — done ♥ http://4ms.me/ieZiLQ<br/>Haha! &quot;@TheQuoteWhore: ☑ Hitler (Done) ☑ Saddam Hussein (Done) ☑ Osama Bin Laden (Done) ☠Justin Bieber (Today) ☠Rebecca Black (Friday)<br/>http://nemkutya.com/2011/05/problem-bieber/ xDDD<br/>ben adımın justin bieber a benzedgını sanmıyorum ya butun bıeber cılar benı takıp edıyor :D<br/>TELL ME WHAT IS HAPPENING TO JUSTIN BIEBER?<br/>Dicen que un #viernes13 nació un tal justin bieber y se predijo que al terminar la primera década del 2000 nos haría la vida una mierda<br/>WYR meet Justin Bieber or Jasmine V? — Justin Bieber http://4ms.me/jFgsxo<br/>- ;Oh how the girl sings beautifully! 
- ;Mom, this is Justin Bieber! : D
hehe<br/>Redbox has the justin bieber movie now @acd2doom :)<br/>May 13: Donald Trump Gets a Book Deal and Justin Bieber Has Obama's Back - msnbc.com Error Reported, We are sorry for that !<br/>KKKKKKKK , Justin Bieber chegou em Hong Kong rodeado de 20 seguranças e foi recepcioado por 7 fãns, #idontbelieveit!<br/>I &lt;3 Justin Bieber<br/>RT @justinbieber: its here. #NSNweekend #NeverSayNeverDVD - http://itunes.apple.com/us/movie/justin-bieber-never-say-never/id425624519<br/>:D soo I didnt get to buy daah Justin Bieber Movie yet.! But will soon.! RT if youu have it already.!<br/>I just took &quot;Your a bad teen, you sneak out, and skip school. Your mom ...&quot; and got: Part 7 : Ouch, That Hurt.! Try it: http://bit.ly/iB8P1d<br/>mn hele tijdlijn is vol over justin bieber.<br/>a chi piace justin bieber ??? 
se dovete fare insulti o cose varie non rispondete<br/>mi futuro marido serà JUSTIN BIEBER! (@sgomez349 live on http://twitcam.com/4venx)<br/>RT if you love Justin Drew Bieber .<br/>Every little boy has a haircut like Justin Bieber -_- but most of them just look like chili bowls<br/>I just took &quot;You and your 3 bestfriends went to Bahamas on a vacation. One day you were...&quot; and got: Part 2 &lt;3! Try it: http://bit.ly/k0bwxW<br/>I just took &quot;You get signed to the same label as Justin Bieber and hes posing for pict...&quot; and got: Part 24 &lt;3! Try it: http://bit.ly/mqGUyj<br/>ahahaRT @arinurcahya: Gue kira hayley beneran lg dgrin justin bieber (¬_ ¬&quot;) RT @indrawwrr: #nowplaying Justin Bieber - One Less Lonely Girl<br/>Lady Gaga, Justin Bieber, And Others Are Entertainers And Nothing ...: facebook justin bieber… http://goo.gl/6HLE<br/>MNT ..BIEBER FACTS In french : )<br/>I just took &quot;A 12 year old and 16 year old could never be dating until y...&quot; and got: 3: HEEELLLLOOOO BAHAMAS!! Try it: http://bit.ly/mksZGq<br/>RT @ProjectOLLG: #thingsgirlswantboystodo Make us feel like One Less Lonely Girl like Justin Bieber.Tell us we're amazing just the way we are like Bruno Mars<br/>RT @evenpro: Para los fanáticos de Justin Bieber, esta es la cuenta del Club de Fans en Venezuela ---&gt; @JBieberVenezla<br/>RT @evenpro: Para los fanáticos de Justin Bieber, esta es la cuenta del Club de Fans en Venezuela ---&gt; @JBieberVenezla<br/>I just took &quot;A 12 year old and 16 year old could never be dating until you me...&quot; and got: 8: Juvie For Bestie! Try it: http://bit.ly/mlzEew<br/>Twitter.com Justin Bieber: Twitter Com Justin Bieber 6 - justin bieber first step forever… http://goo.gl/6HLE<br/>Want to see. RT @AmazonVideo...Justin Bieber: Never Say Never available at Amazon Instant Video. http://amzn.to/m4mfdA<br/>Sel y Justin Bieber viven un tórrido romance que algunos creen que podría ser eterno, pero Sel sabe que tiene que pisar tierra. #BreathBySEL<br/>Get lost twitter over capcity my ass
Peace&lt;3&amp;bieber<br/>baby baby baby ohh!!! RT @Feris_Othman: You sound like Justin Bieber.<br/>Dr bieber RT @JBIndonesiaa: #ajl1 r-d-e-b-e-i-r-b (skype cody)<br/>RT @justinbieber: its here. #NSNweekend #NeverSayNeverDVD - http://itunes.apple.com/us/movie/justin-bieber-never-say-never/id425624519<br/>Justin Bieber Official Site: Justin Bieber Official Site 11 - justin bieber poster never say… http://goo.gl/6HLE<br/>RT @Nooahx: RT @dominiquebiebz: i speak bieberish my blood is purple i live in bieber's world justin bieber is my hero and i'm a proud belieber♥♥<br/>OH MY GOD, FACE IT YOUR SURNAME IS NOT BIEBER AND YOU ARE NOT GOING TO MARRY HIM. Arg.<br/>&quot;Justin Bieber, lo más perfecto que he visto.&quot; #JAJANOMAMEN!<br/>@Stepzzz wat je hebt justin bieber gezien nho :p<br/>Music Videos Of Justin Bieber: Music Videos Of Justin Bieber 9 - justin bieber test your superfan… http://goo.gl/6HLE<br/>@TheBieberHelp oh okay JUSTIN DREW BIEBER ;) &lt;3<br/>Feeling sick calls for a pedicure and polish change. My color of choice... Justin Bieber purple. <br/>@justinbieber http://news.getmusicasia.com/2011/05/11/justin-bieber-live-in-philippines/
~CharisseJustinBieber love you!!!<br/>I LOVE JUSTIN BIEBER I LOVE JUSTIN BIEBER I LOVE JUSTIN BIEBER I LOVE JUSTIN BIEBER<br/>So my son tells me he's gonna get me  a Justin Bieber cake for my Birthday<br/>I liked a @YouTube video http://youtu.be/mnx6kD6A7rQ?a Ryan Beatty - U Smile Justin Bieber Cover<br/>SELENA GOMEZ CONFESSA QUE COMENTÃRIOS DE FÃS DE JUSTIN BIEBER A MACHUCAM! http://bit.ly/kpalnR<br/>MY BIEBER FEVER IS COMING BACK!!!!!!:):):)<br/>100;
var refresher = setTimeout("refresh()",1000);

}

</script>
</head>

Basically, because the PHP code is executed before the page is returned to the page, the content that is fetched is effectively a static string in the javascript code, not something that will ever change.

What you need to do is add a separate PHP script that just fetches the new content and then have your Javascript make an AJAX request to periodically fetch the new version of the content from the second PHP script.

This tutorial describes how to do the javascript end of the request. The PHP end will just be a script that performs your curl requests and returns the output:

<?php
// fetchContent.php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'http://search.twitter.com/search.json?q=bieber&rpp=100');

curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

print curl_exec($ch);


curl_close($ch);

exit;


Comment boxes are too short for this, so i'm writing it out as an answer.

here's how your script executes

  1. User hits the script URL
  2. Webserver fires up the PHP script
  3. Inside the script, CURL fetches the Twitter text, and inserts it into the page's javascript section.
  4. The generated page is sent to the client
  5. The php script exits, the webserver finishes sending the page to the user, and shuts down the connection
  6. The user's browser loads up the page, displays it
  7. The 'refresh' function is called
  8. The refresh function takes the text that was inserted at step #3 and re-inserts it into the page
  9. goto #7

Notice that in steps 7-9 that PHP and the webserver are NOT used again, so the twitter text is NOT changed.

What you've done is the equivalent of writing something on a piece of paper, handing it to someone, and telling them to go over there read what's on the paper every 5 minutes.

What you need to do is tell that person to phone home instead, so your server can fetch another chunk of twitter text and read it out to the person over the phone. And when they're done reading the text, they should phone in again for another set of text.


You can have php write out JavaScript but not the other way around because php is server side and executes first.

0

精彩评论

暂无评论...
验证码 换一张
取 消