在按钮单击时将php变量传递给javascript函数

时间:2016-10-30 09:22:06

标签: javascript php jquery html

我正在显示动态表格。 问题是当我将php变量传递给javascript函数时,它显示错误Unterminate string literal。 我是php的新手,所以我不知道我们如何传递变量。

       <?php
        include 'dbConf.php';
        session_start();
       if($_SERVER["REQUEST_METHOD"] == "POST"){
        if(isset($_POST["submit"]))
          {    

            $username=$_SESSION["username"];
            $productName=$_POST["productName"];
            $quantity=$_POST["quantityRequired"];
            $row = mysqli_query($conn,"INSERT into TR_Order_Details_Dummy values('$username','$productName','$quantity')");
            if(!$row) {
               die('Could not enter data: ' . mysqli_error($conn));
            }
            else{
            $result=mysqli_query($conn,"SELECT * from Order_Details where Username='".$username."' ");
            }
           }
           else
           {
            echo "dummy";
           }
      }

   ?>
<html>
   <head>
       <title>Order Details Page</title>
       <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

   </head>
 <body>
      <table id="table1">
        <th>
           <tr></tr>
           <tr>Username</tr>
           <tr>Product Name</tr>
           <tr>Quantity</tr>
        </th>
        <?php
       while($res = mysqli_fetch_array($result)) {         
            echo "<tr>";
            echo "<td>".$res['Username']."</td>";
            echo "<td>".$res['ProductName']."</td>";
            echo "<td>".$res['Quantity']."</td>";  
            $username=$res['Username'];  
            echo "<td><input type=\"button\" value=\"Edit\" onClick=\"editItem('\".$username.\"')\"> <a href=\"delete.php\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";        
        }
        ?>
      </table>
   </form> 
    <script>
      function addItem()
      {
        window.location.href="order.php";
      }
      function editItem(username)
      {
        $.ajax({
          type:"POST",
          url:"edit.php",
        });
        return false;
      }
    </script>
 </body>  
</html>

2 个答案:

答案 0 :(得分:0)

以下行不正确。

echo "<td><input type=\"button\" value=\"Edit\" onClick=\"editItem('\".$username.\"')\"> <a href=\"delete.php\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";

您需要在字符串中连接$username,以便不应使用\反斜杠转义它周围的引号。

这是修改后的代码。

echo "<td><input type=\"button\" value=\"Edit\" onClick=\"editItem('".$username."')\"> <a href=\"delete.php\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>"; 

答案 1 :(得分:0)

使用此命令行尝试您的代码

<input type=\"button\" value=\"Edit\" onClick=\"editItem('".$username."')\">