如何将元素 id 放入 PHP 变量

san*_*nta 5 php mysql

是否可以将元素id放入PHP变量中?

假设我有许多带有 ID 的元素:

<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
Run Code Online (Sandbox Code Playgroud)

我如何将其放入PHP变量以提交查询。我想我将不得不重新提交该页面,这是可以的。我想使用POST。我可以做这样的事情:

<script language="JavaScript">
$(document).ready(function(){
    $(".myElement").click(function() {
        $.post("'.$_SERVER['REQUEST_URI'].'", { id: $(this).attr("id") });
    });
});
</script>
Run Code Online (Sandbox Code Playgroud)

我需要$(this).attr('id')进入$newID才能运行

SELECT * from t1 WHERE id = $newID
Run Code Online (Sandbox Code Playgroud)

jQuery 是一个非常强大的工具,我想找出一种方法将其功能与服务器端代码结合起来。

谢谢。

Lax*_*n13 4

这就像你的问题:ajax post with jQuery

如果您希望将所有内容都保存在一个文件中(发布到活动文件),那么您通常需要以下内容:

<?php 
  // Place this at the top of your file
  if (isset($_POST['id'])) {
    $newID = $_POST['id'];  // You need to sanitize this before using in a query

    // Perform some db queries, etc here

    // Format a desired response (text, html, etc)
    $response = 'Format a response here';

    // This will return your formatted response to the $.post() call in jQuery 
    return print_r($response);
  }
?>

<script type='text/javascript'>
  $(document).ready(function() {
    $('.myElement').click(function() {
      $.post(location.href, { id: $(this).attr('id') }, function(response) {
        // Inserts your chosen response into the page in 'response-content' DIV
        $('#response-content').html(response); // Can also use .text(), .append(), etc
      });
    });
  });
</script>

<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>

<div id='response-content'></div>
Run Code Online (Sandbox Code Playgroud)

从这里您可以自定义查询和响应以及您想对响应执行的操作。