【问题标题】:HTML & PHP - Type a telephone number, and call itHTML & PHP - 输入电话号码,然后拨打电话
【发布时间】:2015-12-27 13:27:08
【问题描述】:

我写了一个代码,但它不起作用。

代码:

<?php
$number = $_GET["tel"];
echo '<form action="/" method="get">
         <a>Enter the phone number, what you want to call</a>
         <input type="tel" name="tel"/>
         <input type="submit" onclick="call()" value="Call"/>
      </form>
      <script>
          function call() {
              window.open("tel:$number");
          }
      </script>
';

【问题讨论】:

  • 您正在混合使用 php 和 javascript。当用户点击提交按钮时,会调用 javscript 函数,但这对 $number 没有任何价值;因为只有在提交表单之后才会设置。

标签: javascript php html phone-number phone-call


【解决方案1】:

在 PHP 中,字符串中的变量只允许使用 双引号。将单引号更改为双引号,以使 $number 在字符串中起作用。

更多详情请见this SO post

因此,您的代码应如下所示:

<?php
    $number = $_GET["tel"];
    echo "<form action='/' method='get'>
                <a>Enter the phone number, what you want to call</a>
                <input type='tel' name='tel' />
                <input type='submit' onclick='call()' value='Call' />
            </form>
            <script>
                function call() {
                    window.open('tel:$number');
                }
            </script>
        ";
?>

但是这段代码很奇怪。以下是它的流动方式:

  1. get $_GET variable tel(假设表单已经发送)
  2. echo 出表格
  3. 在提交表单时,访问了$_GET["tel"]中的数字,不是表单中的数字
  4. 然后,表单被提交,但这不起作用,因为 window.open() 已经发生

这是一个没有 PHP 的替代解决方案(并且没有实际的表单发送):

<form action='/' method='get'>
<a>Enter the phone number, what you want to call</a>
    <input type='tel' name='tel' />
    <input type='submit' onclick='call();return false;' value='Call' />
</form>
<script>
    function call() {
        var number = document.querySelector("input[name=tel]").value;
        window.open('tel:' + number);
    }
</script>

JSFiddle.net查看它。

【讨论】:

  • 它打开一个新页面,并且url是tel:,所以它不起作用
  • @Bence8OS 您的代码有点混乱:您尝试将表单发送到 PHP,PHP 会将变量放入 JS。相反,您只需要 JS。我将展示一个例子。你根本不需要 PHP
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-09
  • 1970-01-01
  • 1970-01-01
  • 2016-08-11
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多