2015-07-13 84 views
0

請原諒我糟糕的英語。javascript + php不起作用

我想得到'本月有多少周'以及那周的循環數。 (當我檢查php值'$ weekcnt'的正確數字,但不啓動循環。)請幫助我,並告訴我什麼是我的問題。

<script> 
    //How many week in this month 
    var calcWeekCountInTargetYearAndMonthByDate = function(year, month, day) { 
     var d = new Date(year, month, day); 
     return Math.floor((d.getDate() - d.getDay() + 12)/7); 
    } 
    //Get this month's last day 
    var calcThisMonthEndDate = function(year, month){ 
     var dt = new Date(year, month, 0).getDate(); 
     return dt; 
    } 
</script> 
<?php 
    //How many week in this month 
    $weekcnt = '<script type="text/javascript">document.write(calcWeekCountInTargetYearAndMonthByDate(2015, 6, calcThisMonthEndDate(2015,6)));</script>'; 
    echo "There is ".$weekcnt." Weeks <br>"; 
    //number of loop of the week 
    for($tablecnt = 0; $tablecnt < $weekcnt; $tablecnt++) 
    { 
     echo "NOW = ".$tablecnt; 
     //Test print 
    } 
?> 

結果(谷歌瀏覽器)

There is 5 Weeks 
+2

你不能在PHP中獲取一個javascript的結果! php是serverside ...所以你很高興通過ajax或form將javascript的結果發送到你的腳本或使用php函數計算週數。 – donald123

+0

@ donald123非常感謝你的回答!我會嘗試Ajax或找到其他方式。(僅限PHP等)再次感謝您! – user3452170

回答

1

你不能做到這一點... PHP在服務器一側的JavaScript是隻在客戶端執行評估。

可以,或者只是用PHP

單獨做使用javacript相同
var calcWeekCountInTargetYearAndMonthByDate = function (year, month, day) { 
    var d = new Date(year, month, day); 
    return Math.floor((d.getDate() - d.getDay() + 12)/7); 
} 
//Get this month's last day 
var calcThisMonthEndDate = function (year, month) { 
    var dt = new Date(year, month, 0).getDate(); 
    return dt; 
} 
var num = calcWeekCountInTargetYearAndMonthByDate(2015, 6, calcThisMonthEndDate(2015, 6)); 

var text = 'There is ' + num + ' Weeks <br>'; 
for (var i = 1; i <= num; i++) { 
    text += 'NOW = ' + i + '<br />'; 
} 
document.write(text); 
+0

非常感謝你!我會嘗試一下Just php的方式,因爲我必須使用php和mysql。 – user3452170