dongsui5464 2014-08-28 01:39
浏览 39

JavaScript检查值是否存在然后提交表单

I am using the following code to find the browser location and post it to the next page, but the issue is JavaScript is taking little time to find the browser location and form is posting before the browser location is found, how can I make the form submit only after finding the browser location?

newtest1.php

<html>
<head>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    document.getElementById("getlat").value = position.coords.latitude;
    document.getElementById("getlon").value = position.coords.longitude;
}
getLocation();
</script>
</head>
<body>
<form id="myForm" method="post" action="newtest2.php">
<input type="text" id="getlat" name="getlat" /> 
<input type="text" id="getlon" name="getlon" />
<input type="button" name="myformer" onclick="myFunction();" />
</form>
<script>
function myFunction() {
    document.getElementById("myForm").submit();
}
myFunction();
</script>
</body>
</html>

newtest2.php

<?php
echo $_POST['getlat'];
echo $_POST['getlon'];
?>
  • 写回答

3条回答 默认 最新

  • douxunwei7083 2014-08-28 01:51
    关注

    You could make the submit button disabled by default and remove the disable attribute in case the position was found successfully. So you prevent the form from being submitted before a position is found. But the better way would be to trigger the calculation just by the button and wait for the success response and than do an ajax request with the lan and lon values if needed or just manipulate the dom to display the position without any reload. If your php script is just printing variables which are send by javascript there is no need for the php script. Just print the variables values on the html page using javascript.

    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统