2010-11-28 65 views
0

有沒有什麼辦法可以在不使用GET或POST或REQUEST的情況下獲得html文本字段的值?或者,有沒有什麼辦法讓字段值以相同的形式或頁面在其他地方。PHP Javascript變量幫助

這適用於諸如「詹姆斯」,「系統」等直接值。唯一的問題是我如何使它與HTML字段值

像工作:

<input type = "submit" onclick = " 
<?php $username = "kut"; 
$result = checkname($username); 
if($result) 
{ 
?> alert("success"); <?php 
} 
else {?> alert("failed"); <?php 
}?> 
"> 

我怎麼能代替「吉」與ID =「用戶名」文本字段的值?

<?php $username = "?>document.getElementById('username').value;<?php"?> 

或類似的東西...... ???

總之,我需要一個HTML場其他地方在同一個頁面中的JavaScript函數裏面,在上述javascriptFunction使用PHP ......像()函數

+2

您的服務器不運行任何東西,除非發生GET或POST(或任何動詞)......您在這裏要做什麼? – 2010-11-28 16:26:28

+1

您在提交前是否嘗試檢查文本字段值?聽起來像你試圖做一個Ajax電話。 – kjy112 2010-11-28 16:34:12

回答

0

1>我建議的價值使用jQuery來處理Ajax部分。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<script> 
    function check_user(){ 
     var user_el=document.getElementById('username'); 
     if(!user_el){ return false; } 
     var username=user_el.value; // this could all be replaced with $('username').val() 
     $.getJSON('check_var.php',{"user":username},function(data){ 
      if(data.result=='error'){ alert('something was wrong with the PHP stuff'); } 
      alert(data.userstatus); 
      }); 
     } 
</script> 

2>在PHP方面,由於check_var.php,你需要一個腳本,需要用戶名輸入,檢查數據庫,併發送回JSON作爲結果的數據。

<?php 
if(!isset($_GET['user']){ exit; } 

$username=preg_replace('#['^\w\d]#','',$_POST['user']); 

//do your database query. I assume you have that part all set. 
//since I'm not filling in all of that, you'll need to fix this next part to work with your system 
//let's pretend it's like $found=check_user($username); 
//be sure to use mysql_real_escape_string or prepared statements on the $username var since you're working with user input 

$status=$some_db_error ? 'error' : 'success'; 

$results=array('result'=>$status,'userstatus'=>$found); 
header('Content-Type: application/json'); 
echo json_encode($results); 
1

您不能在JavaScript中直接調用PHP函數。您可以在頁面加載前通過echo從php中設置JavaScript值。 PHP在客戶端執行時在服務器上執行。

2

您對客戶機 - 服務器體系結構的工作原理有着根本性的誤解。

PHP可以在距離JavaScript所在的地方數千英里遠的地方執行,甚至幾天。

第一個PHP生成整個頁面,所有的HTML,所有的JavaScript源代碼(未執行),然後,PHP完成後,瀏覽器開始運行JavaScript。

這兩個不能像你想要的那樣混合在一起,即使它在PHP源代碼中看起來如此。

雖然您可以使用AJAX或類似方式再次與服務器通信,但您可能應該先了解客戶端 - 服務器架構如何工作,並嘗試在沒有AJAX的情況下解決問題(例如,在服務器端處理所有數據或在客戶端處理所有數據側)。