2017-07-26 40 views
-3

PHP代碼:無法找到解決方案幫助我..regarding js和PHP

while($row = mysql_fetch_assoc($arr)) 
    { 
     $id = $row['id']; 
     $user_from = $row['user_from']; 
     $user_to = $row['user_to']; 
     $date = $row['date']; 
     $msg_body = $row['msg_body']; 
     $opened = $row['opened']; 
     if(strlen($msg_body)>150) 
     { 
      $msg_body = substr($msg_body,0,150)."...."; 
     } 
     echo "<div id='toggletext$id' style='background-color:#ADD8E6;padding:6px;' onclick='toggle()'>"; 
     echo "<form method='post'>"; 
     echo "<input type='hidden' id='id1' value=$id>"; 
     echo "<a href='$username'>$username</a>&nbsp"; 
     echo "&nbsp: $msg_body "; 
     echo "</form>"; 
     echo "</div> <hr/>"; 
    } 

**它會響應出現在$ ARR值在DIV的形式使每個$改編行會得到顯示具有獨特的DIV ID **

JS代碼:

function toggle() 
    { 
     var hr = new XMLHttpRequest(); 
     var id = document.getElementById("id1").value; 
     var tx = "toggletext"+id; 
     var fn = document.getElementById(tx); 
     var url = "in.php"; 
     fn.style.backgroundColor = "#fff"; 
     var v = '<?php echo @$username;?>'; 
     var vars = "post="+v+"&id="+id; 
     hr.open("POST", url, true); 
     hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
     hr.onreadystatechange = function() 
     { 
      if(hr.readyState == 4 && hr.status == 200) 
      { 
       var return_data = hr.responseText; 
       document.getElementById("status").innerHTML = return_data; 
      } 
     } 
     hr.send(vars); 
     document.getElementById("status").innerHTML = "processing..."; 
    } 

//問題是...當有2個格(如果$ ARR有2行)..如果我點擊第二個div第一個div將被選中..

+1

僅供參考,[你不應該在新代碼中使用'mysql_ *'函數](http://stackoverflow.com/questions/12859942/)。他們不再被維護[並被正式棄用](https://wiki.php.net/rfc/mysql_deprecation)。看到[紅盒](http://php.net/manual/en/function.mysql-connect.php)?學習[*準備的語句*](https://en.wikipedia.org/wiki/Prepared_statement),並使用[PDO](http://php.net/pdo)或[MySQLi](http:// php.net/mysqli) - [這篇文章](http://php.net/manual/en/mysqlinfo.api.choosing.php)將幫助你決定哪一個最適合你。 –

+2

你的id ='id1''總是返回第一個id,只有你需要改變它...嘗試使用'MySqli'' – Nawin

+0

'id's總是需要唯一。 ''然後爲'var id ='使用'this'並找到您的值。這將更容易與jQuery。 – chris85

回答

0

更改您的ID在你輸入型隱藏

echo "<input type='hidden' id='id".$id."' value=$id>"; 

,並得到這樣在你的JavaScript ...

var incval = '<?php echo $id ?>'; 
var id = document.getElementById("id"+incval).value; 

我給PHP的回聲,因爲你已經調用用戶名... 最後,試着用My_Sqli函數代替my_sql

+0

'$ username'是全局變量...'$ id'是局部變量..我們不能回顯$ id ..現在如何在js中提取'id $ id'@Nawin – rahul

+0

然後你可以使用'$(this )'而不是id,並且需要聲明類名 – Nawin

+0

@rahul以供參考http://jsfiddle.net/DU8rd/1/ – Nawin

相關問題