为什么这个Javascript在与php混合时不起作用


why doesnt this Javascript work when mixed with php?

im 试图通过 PHP curl 从 Twitter 获取搜索项目,每秒处理和更新它们。在这个简单的版本中,我只是试图每秒刷新"比伯"的搜索结果。我已经将PHP与JavaScript结合在一起,我猜这是事情不起作用的原因......但我需要了解为什么。在我的理解中,Apache只将html发送回浏览器...那么为什么内部HTML规范有问题:这是脚本

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

我知道有 AJAX 和 JQuery 等,但只有在我们向我解释了为什么这段代码有问题以及为什么没有这些技术就不可能做什么之后,我们才提到它们。

谢谢!

看看在服务器端执行 PHP 后返回到浏览器的 HTML 源代码:

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

基本上,由于PHP代码是在页面返回到页面之前执行的,因此获取的内容实际上是javascript代码中的静态字符串,而不是永远不会更改的内容。

你需要做的是添加一个单独的PHP脚本,它只获取新内容,然后让你的Javascript发出AJAX请求,定期从第二个PHP脚本中获取新版本的内容。

本教程介绍如何执行请求的 javascript 结束。PHP 端只是一个脚本,它执行你的 curl 请求并返回输出:

<?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;

注释框太短了,所以我把它写出来作为答案。

以下是脚本的执行方式

  1. 用户点击脚本网址
  2. Web服务器启动PHP脚本
  3. 在脚本中,CURL 获取 Twitter 文本,并将其插入页面的 javascript 部分。
  4. 生成的页面将发送到客户端
  5. php 脚本退出,Web 服务器完成向用户发送页面,并关闭连接
  6. 用户的浏览器加载页面并显示它
  7. 调用"刷新"函数
  8. 刷新函数获取在步骤 #3 中插入的文本,并将其重新插入到页面中
  9. 转到 #7

请注意,在步骤 7-9 中,PHP 和 Web 服务器不会再次使用,因此 Twitter 文本不会更改。

你所做的相当于在一张纸上写一些东西,把它交给某人,然后告诉他们每5分钟去那边读一次纸上的内容。

你需要做的是告诉那个人打电话回家,这样你的服务器就可以获取另一块Twitter文本,并通过电话读给那个人。当他们读完文本后,他们应该再次打电话获取另一组文本。

你可以让 php 写出 JavaScript,但不能反过来,因为 php 是服务器端并且首先执行。