如何获取元素ID到PHP变量中 [英] How to get element id into PHP variable

查看:76
本文介绍了如何获取元素ID到PHP变量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to get an element id into a PHP variable?

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

Let's say I have a number of element with IDs:

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

如何将其放入PHP变量中以便提交查询.我想我必须重新提交页面,这是可以的.我想使用POST.我可以做类似的事情吗?

How do I get this into a PHP variable in order to submit a query. I suppose I would have to resubmit the page, which is OK. I would like to use POST. Can I do something like:

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

我需要将$(this).attr('id')传递到$newID才能运行

I need to pass $(this).attr('id') into $newID in order to run

SELECT * from t1 WHERE id = $newID

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

jQuery is a very powerful tool and I would like to figure out a way to combine its power with server-side code.

谢谢.

推荐答案

这就像您的问题: ajax jQuery发布

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

If you want this all in one file (posting to active file) here is what you would need in general:

<?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>

您可以在此处自定义查询和响应以及您希望对响应执行的操作.

From here you can customize the queries and response and what you would like to do with the response.

这篇关于如何获取元素ID到PHP变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆