Jquery传递变量到没有形式的帖子?

时间:2013-10-25 14:02:14

标签: jquery

在我的超级用户页面中删除并修改我以这种方式完成的用户

<table>
    <tr>
       <td>USERID</td>
       <td>NAME</td>
       <td>AGE</td>
       <td>DELETE</td>
       <td>MODIFY</td>
    </tr>

    <?php

    $base_url = 'this_page.php';

    $query = "SELECT * FROM tbl";
    $result = mysql_query($query);
    while ($row = mysql_fetch_array($result)) {


    $btn_del = "<input type='button' ";
    $btn_del .= "onClick=\"location.href='" . $base_url . "&action=Delete&id=$row[userid]'\" ";
    $btn_del .= "class='deluser' />";

    $btn_mod = "<input type='button' ";
    $btn_mod .= "onClick=\"location.href='" . $base_url . "&action=Modify&id=$row[userid]'\" ";
    $btn_mod .= "class='moduser' />";

    echo "<tr>\n";
        echo "<td>" . $row['userid'] . "</td>\n";
        echo "<td>" . $row['user'] . "</td>\n";
        echo "<td>" . $row['age'] . "</td>\n";
        echo "<td>" . $btn_del . "</td>\n";
        echo "<td>" . $btn_mod . "</td>\n";
    echo "</tr>";


    }

</table>


    <?php

    switch ($_GET['action']) {

    case "Delete":

        // call delete method of user class
        $obj->DeleteUser($_GET['idric']);

        echo "<script>";
        echo "document.location.href=\"$base_url\"";
        echo "</script>";

        break;

    case "Modify":

        // call modify method of user class
        $obj->ModifyUser($_GET['idric']);   

        echo "<script>";
        echo "document.location.href=\"$base_url\"";
        echo "</script>";

        break;

    }               

    ?>

这种方式运作得体,但我想做一些更优雅的事情,可能使用jquery post和/或ajax。

到目前为止,我已经使用jquery通过表单传递数据(用于验证)。

// # Form Submit
$(".Form").submit(function( event ) {

event.preventDefault();

$.post("action.admin.php", {

  name: $("#name").val(),
  age: $("#age").val(),
  userid: $("#userid").val()
  },
});

如何在不使用带有jquery帖子的表单的情况下将我的数据传递给action.php(在本例中为$ userid)?

// # click
$(".deluser").click(function( event ) {

 event.preventDefault();

$.post("action.php", {
??
??

由于

2 个答案:

答案 0 :(得分:2)

您实际上并没有使用form来构建值(就像使用.serialize()函数一样)。看看你的代码:

$.post("action.admin.php", {
  name: $("#name").val(),
  age: $("#age").val(),
  userid: $("#userid").val()
});

每个键/值对都有一个显式键,然后从$('#someElement').val()获取其值。它们都不依赖于form标签。这些元素(#name等)可以存在于具有id值的页面上的任何位置,这仍然有用。

您可以这种方式使用您想要的任何值:

$.post("action.admin.php", {
  name: $("#name").val(),
  age: 'someString',
  userid: aVariableInitializedSomewhereElse
});

答案 1 :(得分:1)

使用数据参数

$.ajax({
  type: "POST",
  url: url,
  data: {
      // Your data here
  },
  success: success,
  dataType: dataType
});