奇怪的JavaScript,PHP和Google Maps行为

时间:2011-03-31 13:10:11

标签: php javascript google-maps

我在这种情况下打破了我的大脑:)

我有一张表格:

<form method="post" action="">
   <input type="hidden" name="entered_markers"
   value="<script type='text/javascript'> document.getElementById('rout_markers').value; </script>" />
 <input type="submit" value="Enter the trees you saw!" />
</p>
</form>

如您所见,entered_markers尝试传递一些JavaScript变量。

当我处理请求时,我这样做

$chosen_markers = $_POST['entered_markers'];

然后奇怪的部分:)

if ( empty ($chosen_markers) || !isset($chosen_markers) )  {
      $errors[] = 'Please click on the map to select spots where you spotted these tree. Markers: '.$chosen_markers;
} else {
   // Set something to signify that things are ok
}

我总是得到结果,验证认为输入不是空的,但当我尝试使用该变量$ rout_markers时,它就没有任何内容。

我在哪里错了?这不是一件奇怪的事吗? :)

4 个答案:

答案 0 :(得分:2)

$rout_markers替换为$chosen_markers

答案 1 :(得分:1)

试试这个:

<form method="post" action="" onsubmit="document.getElementById('entered_markers').value = document.getElementById('rout_markers').value;">
    <p>
        <input type="hidden" name="entered_markers" id="entered_markers" value="" />
        <input type="submit" value="Enter the trees you saw!" />
    </p>
</form>

修改:并按照webarto的建议将$rout_markers替换为$chosen_markers

答案 2 :(得分:1)

下面的代码可能会解释你可能做错了什么。

$errors = array();

if (
    isset($_POST['entered_markers']) // make sure the variable is available
) {

    if (
        is_string($_POST['entered_markers']) // make sure the data type is string (could be array when form is manipulated)
    ) {

        $markers = trim($_POST['entered_markers']); // trim whitespace and store it in a var

        if ($markers !== "") { // if the string is NOT empty

            echo "Input given!";
            // At this point you could add some more validation to check whether the given input is also what you expect it to be.
            // Preform a regexp for lat/lng for example.
            echo $markers;

        } else {
            $errors[] = "Parameter 'entered_markers' is empty.";
        }

    } else {
        $errors[] = "Parameter 'entered_markers' is not a string.";     
    }

} else {
    $errors[] = "Parameter 'entered_markers' is not found.";
}

print_r($errors);

答案 3 :(得分:1)

通过在头脑中创建JavaScript函数并将表单作为参数传递来解析它的输入字段来尝试它。我继续创建了一个虚拟文本字段名称“rout_markers”并给它一个值300.所以,在你的PHP端,如果你查找$_POST['entered_markers'],如果你使用下面的例子,它将回显为300:

<html>
<head>
<script type='text/javascript'>
    function submitCoor(form){
        form['entered_markers'].value = document.getElementById('rout_markers').value;
    }
    </script>
</head>
<body>
<input type='text' value='300' id='rout_markers' />
<form method="post" action="test.php" onsubmit="submitCoor(this)">
    <input type="hidden" name="entered_markers"
    value="" />
    <input type="submit" value="Enter the trees you saw!" />
</form>
</body>
</html>