如何将元素 id 放入 PHP 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5163197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:59:46  来源:igfitidea点击:

How to get element id into PHP variable

phpmysql

提问by santa

Is it possible to get an element idinto a PHPvariable?

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

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

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

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

How do I get this into a PHPvariable 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:

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

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

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

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

SELECT * from t1 WHERE id = $newID

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

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

Thanks.

谢谢。

采纳答案by Laxman13

This is like your question: ajax post with jQuery

这就像你的问题:ajax post with 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.

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

回答by Steven

You have two "good" choices in my mind.

你有两个“好”的选择。

The first is to initiate a post request every time the ordering changes. You might be changing the ordering using jQuery UI sortable. Most libraries that support dragging and dropping also allow you to put an event callback on the drop simply within the initialization function.

第一种是在每次排序发生变化时发起 post 请求。您可能正在使用jQuery UI sortable更改排序。大多数支持拖放的库还允许您在初始化函数中简单地将事件回调放在拖放上。

In this even callback, you'd initiate the $.postas you have written it in your code (although I would urge you to look up the actual documentation on the matter to make sure you're POSTing to the correct location).

在这个偶数回调中,您将$.post按照您在代码中编写的方式启动它(尽管我会敦促您查看有关此事的实际文档,以确保您发布到正确的位置)。

The second strategy is to piggyback on a form submission action. If you're using the jQuery Form Pluginto handle your form submissions, they allow you to indicate a before serialize callback where you can simply add into your form a field that specifies the ordering of the elements.

第二个策略是搭载表单提交操作。如果您使用jQuery 表单插件来处理表单提交,它们允许您指示一个 before 序列化回调,您可以在其中简单地向表单添加一个指定元素顺序的字段。

In both cases, you'd need to write your own function that actually serializes the element IDs. Something like the following would do just fine (totally untested; may contain syntax errors):

在这两种情况下,您都需要编写自己的函数来实际序列化元素 ID。像下面这样的东西就可以了(完全未经测试;可能包含语法错误):

var order = [];
$('span.myElement').each(function(){
  // N.B., "this" here is a DOM element, not a jQuery container
  order.push(this.id); 
});
return order.join(',');

回答by Explosion Pills

Your approach looks perfectly fine to me, but jQuery does not have a $_SERVER variable like PHP does. The url you would want to provide would be window.location(I believe an empty string will also work, or you can just specify the url on your own). You seem to be sending the ID just fine, though, so this will work.

您的方法对我来说看起来非常好,但是 jQuery 没有像 PHP 那样的 $_SERVER 变量。您想要提供的网址是window.location(我相信空字符串也可以,或者您可以自己指定网址)。不过,您似乎可以很好地发送 ID,因此这将起作用。

If you want the page to react to this change, you can add a callback function to $.post(). You can do a variety of things.

如果您希望页面对此更改做出反应,可以向$.post(). 你可以做各种各样的事情。

$.post(window.location, {id: this.id}, function (data) {
   //one
   location.reload();
   //two
   $("#responsedata").html(data);
   //three
   $("#responsedata").load("affected_page.php #output");
});

I think number 2 is the most elegent. It does not require a page reload. Have your server side php script echo whatever data you want back (json, html, whatever), and it will be put in dataabove for jQuery to handle however you wish.

我认为2号是最优雅的。它不需要重新加载页面。让您的服务器端 php 脚本回显您想要返回的任何数据(json、html 等),并将其放在data上面,以便 jQuery 处理您想要的任何数据。

By the way, on the server side running the query, don't forget to sanitize the $id and put it in quotes. You don't want someone SQL Injecting you.

顺便说一句,在运行查询的服务器端,不要忘记清理 $id 并将其放在引号中。您不希望有人向您注入 SQL。

回答by Dan

You're quite right, something along those lines would work. Here's an example:

你说得对,沿着这些路线的东西会起作用。下面是一个例子:

(btw, using $.postor $.getdoesn't resubmit the page but sends an AJAX request that can call a callback function once the server returns, which is pretty neat)

(顺便说一句,使用$.post$.get不重新提交页面,而是发送一个 AJAX 请求,该请求可以在服务器返回后调用回调函数,这非常简洁)

<script language="JavaScript">
$(document).ready(function(){
    $(".myElement").click(function() {
        $.post(document.location, { id: $(this).attr("id") },
          function (data) { 
              // say data will be some new HTML the server sends our way
              // update some component on the page with contents representing the element with that new id
              $('div#someContentSpace').html(data);
          });
    });
});
</script>