Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用jQuery在PHP中定义变量_Php_Jquery_Html - Fatal编程技术网

使用jQuery在PHP中定义变量

使用jQuery在PHP中定义变量,php,jquery,html,Php,Jquery,Html,我想在PHP中定义变量时使用JQuery 假设我有以下index.php文件: <!DOCTYPE html> <html> <head> <title>Page</title> <script type="text/javascript" src="../../../resources/js/common/jquery-latest.min.js"></script> </head>

我想在PHP中定义变量时使用JQuery

假设我有以下
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>
但它不起作用

预期结果应为:

样本1 样本3


编辑:我不能使用AJAX。您可以使用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);
  }
});
在PHP脚本中,您可以获得所需段落的值,如下所示:

 $answer1 = $_POST['answer1'];
 echo $answer1;
 $answer2 = $_POST['answer2'];
 echo $answer2;
当然,如果要将post值插入数据库中,必须对其进行清理,但这是一件全新的事情

我希望这能让你开始


您可以阅读更多关于AJAX的信息,这可能吗?应该是第一个问题。您的代码无法工作,因为您试图在PHP中使用jQuery。如果您需要将值传递给PHP,您应该通过jQuery获取它们,并使用ajax将它们传递给PHP脚本。或者至少不是你怎么尝试的。不能在PHP内部使用Javascript。Javascript运行客户端,PHP运行服务器端。他们不能像你尝试的那样交流。您必须使用例如AJAX将值从JS传递到PHP。编辑:Blady更快了:你需要了解客户机和服务器。所有javascript/jquery代码都在浏览器中运行,这发生得很晚,因为服务器的响应已经运行并显示在浏览器中。请阅读:@a.Lau,看到了,但只要他使用jquery,我不明白他为什么不能使用AJAX。
 $answer1 = $_POST['answer1'];
 echo $answer1;
 $answer2 = $_POST['answer2'];
 echo $answer2;