如何将变量从javascript发送到php

osh3o9ms  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(323)

我想知道如何将变量从javascript发送到php,以便创建一个包含动态行和的变量。
更具体地说:当我在搜索框中搜索时,我想得到行数(1个匹配项是1行,2个匹配项是2行,依此类推)
我尝试实现这个:document.getelementbyid(“i1”).value=allcells.length;所以我后来可以调用php,但我没有工作。
这是我的javascript,顺便说一句,javascript工作得很完美。

  1. <script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
  2. <script language="javascript" type="text/javascript">
  3. $(document).ready(function()
  4. {
  5. $('#search').keyup(function() {
  6. searchTable($(this).val());
  7. });
  8. });
  9. function searchTable(inputVal)
  10. {
  11. var table = $('.table');
  12. table.find('tr').each(function(index, row)
  13. {
  14. var allCells = $(row).find('td');
  15. if (allCells.length > 0) {
  16. var found = false;
  17. allCells.each(function(index, td)
  18. {
  19. var regExp = new RegExp(inputVal, 'i');
  20. if (regExp.test($(td).text()))
  21. {
  22. found = true;
  23. return false;
  24. document.getElementById("i1").value = allCells.length;
  25. }
  26. });
  27. if (found == true)
  28. $(row).show();
  29. else
  30. $(row).hide();
  31. }
  32. });
  33. }
  34. $(function()
  35. {
  36. $('#table a').click(function(e)
  37. {
  38. e.preventDefault();
  39. $('#result').val($(this).closest('tr').find('td:first').text());
  40. });
  41. });
  42. </script>

我想在我的表格标题中动态地向她吐出行数的总和。

  1. <h3>Total: (<?php print_r($_GET["i1"])?>) </h3>

我希望你能帮助我。

u3r8eeie

u3r8eeie1#

您可能还没有了解javascript和php之间的区别
javascript是clientside,这意味着一切都由本地系统处理。php是服务器端的,这意味着一切都由服务器处理并解析为html。
不能像以前那样将值从javascript发送到普通php中。但是,您可以发送一个post或访问同一个脚本,并让它重新加载脚本的一部分
http://api.jquery.com/jquery.get/
http://api.jquery.com/jquery.post/

roqulrg3

roqulrg32#

我也建议使用ajax或其他东西将javascript值传递给php。您可以创建ajax调用,从javascript添加数据,并在php文件中捕获数据。

  1. var value = "Jan";
  2. $.ajax({
  3. url: "/form.php",
  4. type: "post",
  5. data: "name=" + value
  6. });

在php文件中,可以执行以下操作:

  1. <?php
  2. $catchedName = $_POST["name"];
  3. ?>
n3ipq98p

n3ipq98p3#

你不是第一个想要这样的人,也不是第一个被告知这不可能是你想象的那样。当您浏览到php页面时,基本上是这样的:
浏览器向服务器发送http请求
服务器确定要发送到浏览器的页面
服务器发现您需要一个php页面
服务器执行php
服务器将php返回的内容发送到浏览器
浏览器不知道php,只显示html
浏览器执行javascript。
现在重要的一点是浏览器不知道什么是php,但是可以执行javascript,而服务器不知道什么是javascript(为了简单起见),但是可以执行php。底线:两者之间很难沟通,因为它们是在不同的地方执行的。您很可能希望使用ajax,因此下面是一个超级简单的示例:
我们将获取的php页面:

  1. <?
  2. // We're on the server
  3. // We're going to output something:
  4. echo "Yay! You can see me!"; // So the browser sees only "Yay! You can see me!" (without quotes).
  5. ?>

javascript(使用jquery)获取php页面:

  1. $("#anElementID").load("thePHPPageWeWantToFetch.php"); // It's that simple! The element with the ID #anElementID now contains "Yay! You can see me!" (without quotes).
展开查看全部

相关问题