2014-04-03 24 views
0

我想要一個函數調用一個輸入的php函數。你如何輸入JavaScript變量到PHP腳本?

javascript函數(picNum爲整數):

function hello(picNum) { 
    var pictureNumber = picNum; 

    var phpFunc = "<?php 
     include 'otherfile.php'; 
     otherFileFunc(" + pictureNumber + ") //This is where the problem is, the input(pictureNumber) wont go through 
    ?>"; 
    echo phpFunc; 
} 

otherfile.php

<?php 
    function otherFileFunc($i) { 
     $final = $i + 1; 
     echo $final; 
    } 
?> 

這個代碼,如果你做很多的onclick說= 「你好(1)」那麼輸出或phpFunc應該是2,因爲你在otherfile.php中添加了一個,但無論輸入的輸出總是爲1,所以我猜測輸入在我標記的地方沒有經過。

不要告訴我它不工作,因爲它是。 如果我把一個整數,而不是「+ pictureNumber +」它完美的作品!

任何幫助表示讚賞:)

+3

你感到困惑的服務器端和客戶端之間的區別。簡單地說*這是行不通的*。閱讀Ajax,因爲這是你需要的。 – developerwjk

+0

一旦PHP運行在頁面上,它將不會再運行。它與一個整數完美協作的原因是因爲你用一個數字運行PHP函數並運行該函數。由於PHP只能運行一次,因此如果從JS調用它,'pictureNumber'變量不會改變。 – DNACode

回答

1

不幸的是,你將無法從JavaScript調用PHP。

PHP是從服務器運行和JavaScript是一種客戶端上運行(通常,例外是node.js中但是即使在node.js中的實例,PHP是不使用如JavaScript取代它的功能)

如果您需要讓JavaScript「調用」服務器功能,您需要查看ajax請求,以便服務器可以運行一個函數並將其返回給客戶端。

1

你必須使用Ajax的兄弟:

的Javascript:

function hello(picNum) { 
    var pictureNumber = picNum; 
    $.ajax({ 
    url: "otherfile.php", 
    data: {"picNum":pictureNumber}, 
    type:'post', 
    dataType:'json', 
    success: function(output_string){ 
     PictureNumber = output_string['picturenumber']; 
     alert(PictureNumber); 
    } 
    }); 
} 

PHP otherfile.php:

$picNum = $_POST['picNum']; 
function otherFileFunc($pic){ 
    $final = $pic + 1; 
    return $final; 
} 
$outputnumber = function($picNum); 
$array = ('picturenumber' => $outputnumber); 
echo json_encode($array); 

注:未經測試

編輯,測試:

的javascript:

function hello(picNum) { 
    var pictureNumber = picNum; 
    $.ajax({ 
    url: "otherfile.php", 
    data: {"picNum":pictureNumber}, 
    type:'post', 
    dataType:'json', 
    success: function(output_string){ 
     pictureNumber = output_string['picturenumber']; 
     alert(pictureNumber); 
    } 
    }); 
} 
hello(1); //sample 

PHP otherfile.php:

$picNum = $_POST['picNum']; 
$picNum = 1; 
function otherFileFunc($pic){ 
    $final = $pic + 1; 
    return $final; 
} 
$outputnumber = otherFileFunc($picNum); 
$array = array('picturenumber' => $outputnumber); 

echo json_encode($array); 
+0

不能正常工作....:/ – user2990545

+0

現在嘗試@ user2990545 –