表单提交时页面加载两次

时间:2014-07-05 10:15:10

标签: jquery javascript

我有这个代码从访问者检索数据,然后通过隐藏的输入将数据发送到PHP代码。我在页面加载时发送所有这些数据,因此页面加载两次(正常加载然后表单提交重新加载)。这是代码:

jQuery(function(){
    if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(sendPosition);
        } else { 
            alert("Geolocation is not supported by this browser.");
        }

jQuery(function(){
    function sendPosition(position) {
        var lat =  position.coords.latitude;
        var lng =  position.coords.longitude;



        var form = document.createElement("form");
        form.setAttribute("method", "POST");
        form.setAttribute("action", "");
        form.setAttribute("id", "loc");

        var hiddenField1 = document.createElement("input");
        hiddenField1.setAttribute("type", "hidden");
        hiddenField1.setAttribute("name", "lat");
        hiddenField1.setAttribute("value", lat);

        var hiddenField2 = document.createElement("input");
        hiddenField2.setAttribute("type", "hidden");
        hiddenField2.setAttribute("name", "lng");
        hiddenField2.setAttribute("value", lng);

        form.appendChild(hiddenField1);
        form.appendChild(hiddenField2);
        document.body.appendChild(form);
        form.submit();
        }
});

我确信脚本注册并入队,我没错。有没有办法解决重装?

1 个答案:

答案 0 :(得分:0)

“装载两次”是什么意思? 您发布的代码将在完全加载页面后运行,然后执行表单提交。提交事件将导致页面重新加载。这是你的意思吗?

如果您想在不刷新页面的情况下发布位置数据,您有两个选项:

(A)简单:添加一个不可见的iframe,并将表单“target”属性设置为该iframe。这将导致iframe重新加载,页面的其余部分将不会重新加载。

(B)更好:通过ajax提交数据。这需要您添加接收和处理数据的an ajax handler

在这两种情况下,页面都会提交位置数据但不会刷新。 顺便说一句。你也可以通过jQuery以更好的方式创建那个表单。

示例:

jQuery(function() {
  if (navigator.geolocation) {
    // Add this to find out if the code is called twice:
    alert("Get the user location...");  

    navigator.geolocation.getCurrentPosition(sendPosition);
  } else { 
    alert("Geolocation is not supported by this browser.");
  }

  function sendPosition(position) {
    // Add this to find out if the code is called twice:
    alert("sending the position");

    var lat = position.coords.latitude;
    var lng = position.coords.longitude;

    // Solution (A)
    var iframe = jQuery('<iframe name="dummy"></iframe>')
    var form = jQuery('<form method="POST" target="dummy" action="">'); // Note: target=""
    jQuery('<input type="hidden" name="lat" />').val(lat).appendTo(form);
    jQuery('<input type="hidden" name="lng" />').val(lng).appendTo(form);
    iframe.appendTo('body').hide();
    form.appendTo('body').submit();

    // Solution (B)
    var args = {
      "lat": lat,
      "lng": lng,
      "action": "save-coords"
    };
    jQuery.post(ajaxurl, args, function(resp) { 
      alert( "Server response: " + resp ); 
    });
    // Note: In WordPress you have to add these two ajax handlers:
    // add_action( 'wp_ajax_save-coords', 'my_save_coords' );
    // add_action( 'wp_ajax_nopriv_save-coords', 'my_save_coords' );
  }
});
相关问题