简体   繁体   English

使用jQuery在PHP中定义变量

[英]Use jQuery for defining variable in PHP

I want to JQuery while defining a variable in PHP. 我想在PHP中定义变量时使用JQuery。

Suppose I have the following index.php file: 假设我有以下index.php文件:

<!DOCTYPE html>
<html>
<head>
    <title>Page</title>
    <script type="text/javascript" src="../../../resources/js/common/jquery-latest.min.js"></script>
</head>
<body>
    <div class="bigdaddy">
        <div class="daddy">
            <header class="main"></header>
            <main>
                <aside>
                </aside>
                <article>
                    <div class="div1">
                        Sample1
                    </div>
                    <div class="div2">
                        <div> //Child 1
                            Sample2
                        </div>
                        <p> //Child 2
                            Sample3
                        </p>
                    </div>
                    <?php
                        // the code
                    ?>
                </article>
            </main>
            <footer class="main"></footer>
        </div>
    </div>
</body>
</html>

Questions: 问题:

  • How can I select <div> with attribute and attribute value class="div1" to get its node/inner text? 如何选择具有属性和属性值class="div1" <div>以获得其节点/内部文本?
  • How can I select <p> child of <div class="div2"> its node/inner text? 如何选择<p> <div class="div2">的节点/内部文本的<p><div class="div2">
  • Is it even possible to use jQuery in PHP? 甚至可以在PHP中使用jQuery吗?

Both questions are using jQuery 这两个问题都使用jQuery

I thought of 我想到了

<?php
    $answer1 = $('div[class="div1"]').html();
    echo $answer1;
    $answer2 = $('div.class="div2"').children('p').html();
    echo $answer2;
?>

But it didn't work. 但这没有用。

Expected result should be: 预期结果应为:

Sample1 Sample3 Sample1 Sample3

EDIT: I can't use AJAX. 编辑:我不能使用AJAX。

You can use AJAX to send the data you want to the server, and handle the rest using PHP: 您可以使用AJAX将所需的数据发送到服务器,并使用PHP处理其余数据:

var answer1 = $('.div1').text();
var answer2 = $('.div2').find('p').text();
$.ajax({
  type: 'post',
  url: 'your_php_script.php',
  data: {
    answer1 : answer1, answer2: answer2
  },
  success: function(response_from_php_script) {
    console.log(response_from_php_script);
  }
});

And in your PHP script you can get the value of the paragraph you need like this: 在您的PHP脚本中,您可以像这样获得所需段落的值:

 $answer1 = $_POST['answer1'];
 echo $answer1;
 $answer2 = $_POST['answer2'];
 echo $answer2;

Of course you will have to sanitize the post values if you want to insert it in the database, but that's a whole new thing. 当然,如果要将其插入数据库中,则必须清理发布值,但这是全新的东西。

I hope this will get you started. 我希望这会帮助您入门。

You can read more about AJAX here . 您可以在此处阅读有关AJAX的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM