Javascript 使用POST从iframe向php发送js变量

Javascript 使用POST从iframe向php发送js变量,javascript,php,html,post,Javascript,Php,Html,Post,我正在尝试将一个变量从js传递到后台页面。 到目前为止,我已经尝试使用一个表单并从javascript提交它(但这会刷新页面,这是我不想要的) 我放弃了iframe的表单和时间(因此页面不会在每次提交数据时重新加载)。函数每隔几秒钟运行一次(因此表单应提交): /*一些其他的东西*/ var posSend=document.getElementById(“位置”); posSend.value=pos; posSend.form.submit(); 使用ajax调用提交表单,而不是使用

我正在尝试将一个变量从js传递到
后台
页面。 到目前为止,我已经尝试使用一个表单并从javascript提交它(但这会刷新页面,这是我不想要的)

  • 我放弃了iframe的表单和时间(因此页面不会在每次提交数据时重新加载)。函数每隔几秒钟运行一次(因此表单应提交):

/*一些其他的东西*/
var posSend=document.getElementById(“位置”);
posSend.value=pos;
posSend.form.submit();

使用ajax调用提交表单,而不是使用iframe提交表单而不重新加载

$.ajax({
  type: "POST",
  url: url,
  data: $("#formId").serialize(), // This will hold the form data
  success: success, // Action to perform on success
  dataType: "JSON" or "HTML" or "TEXT" // return type of function
});
有多种方法可以在不重新加载页面的情况下提交表单


谢谢

您可以使用插件ajaxForm。在操作和方法上,您可以形成选项

$(函数(){
$('#form_f')。ajaxForm({
beforeSubmit:ShowRequest,//ShowRequest
成功:submitsuccessful,//成功
错误:AjaxError//error
});

});Lakhan是对的,您应该尝试使用ajax而不是iframe,因为它们会导致很多问题。如果您确实需要使用iframe,请在表单中添加一个target属性(以iframe为目标,而不是以主页面为目标),并且只有iframe将重新加载

<form action="action" method="post" target="target_frame">
    <!-- input elements here --> 
</form>
<iframe name="target_frame" src="" id="target_frame" width="XX" height="YY">
</iframe> 

下面是一个完整的示例,它使用了
FormData
对象和AJAX来完成提交。它将每5秒更新一次页面。请注意,在PHP中,单引号(')和双引号(“)的使用并不总是可互换的。如果使用单引号,则内容按字面形式打印。如果使用双引号,则在字符串包含变量名时解释内容。因为我想将变量名与前面的美元符号($)一起打印我在php文件中使用了单引号

首先是PHP

location.php

<?php
$location = $_POST['location'];
$posSend = $_POST['posSend'];

echo '$location: ' . $location . '<br>';
echo '$posSend: ' . $posSend;
?>

接下来是HTML

index.html

<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}

function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function()
    {
        if (this.readyState==4 && this.status==200)
            successCallback(this);
    }
    ajax.onerror = function()
    {
        console.log("AJAX request failed to: " + url);
        errorCallback(this);
    }
    ajax.open("POST", url, true);
    var formData = new FormData(formElem);
    ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    var submitIntervalHandle = setInterval( doAjaxFormSubmit, 5000 );       // call the function to submit the form every 5 seconds
}

function doAjaxFormSubmit()
{
    myAjaxPostForm('location.php', byId('myForm'), onSubmitSuccess, onSubmitError);
    function onSubmitSuccess(ajax)
    {
        byId('ajaxResultTarget').innerHTML = ajax.responseText;
    }
    function onSubmitError(ajax)
    {
        byId('ajaxResultTarget').innerHTML = "Sorry, there was an error submitting your request";
    }
}

</script>
<style>
</style>
</head>
<body>
    <form id='myForm'>
        <input name='location'/><br>
        <input name='posSend'/><br>
    </form>

    <hr>

    <div id='ajaxResultTarget'>
    </div>
</body>
</html>

“严格使用”;
函数byId(id,parent){return(parent==未定义?文档:parent).getElementById(id);}
函数myAjaxPostForm(url、formElem、successCallback、errorCallback)
{
var ajax=new-XMLHttpRequest();
ajax.onreadystatechange=函数()
{
if(this.readyState==4&&this.status==200)
成功回调(this);
}
ajax.onerror=函数()
{
log(“AJAX请求失败:”+url);
错误回调(本);
}
open(“POST”,url,true);
var formData=新formData(formElem);
发送(formData);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load',onDocLoaded,false);
函数onDocLoaded()
{
var submittintervalhandle=setInterval(doAjaxFormSubmit,5000);//每隔5秒调用函数提交表单
}
函数doAjaxFormSubmit()
{
myAjaxPostForm('location.php',byId('myForm'),onSubmitSuccess,onSubmitError);
函数onSubmitSuccess(ajax)
{
byId('ajaxResultTarget')。innerHTML=ajax.responseText;
}
SubmitError上的函数(ajax)
{
byId('ajaxResultTarget')。innerHTML=“对不起,提交请求时出错”;
}
}




我认为您不需要为此使用表单或iframe。您只需要了解用户onf而不进行刷新,然后使用以下ajax方法

index.html
中的代码将

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script>
    navigator.geolocation.getCurrentPosition(function(position) 
    { 
        pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
        $.ajax(
        {
            url:'location.php',
            type: 'POST',
            datatype: 'json',
            data: {'pos':pos},   // post to location.php
            success: function(data) {
                aler(data);
                // success
            },

            error: function(data) {
                alert("There may an error on uploading. Try again later");
            },

         });  
    });  
    </script>

为什么要像使用表单一样使用iframe?在HTML部分,您将an、a和一个元素混合在一起。它们应该是3个不同的元素。因为表单提交会刷新整个页面,而iframe会粘在一起,不会弄乱页面。@oliver-有什么理由不简单地使用
来收集数据吗
FormData
object将其捆绑到单个对象中,然后最后由a.J.a.X提交?一个
iframe
没有
action
method
属性。我实现了这个atm,但是在获得用户位置后,我如何将其传递到表单中?假设我有变量
pos
,这需要要转到另一个页面,我在函数中的什么位置分配
pos
,ipinfo.io做什么?ipinfo.io获取用户位置,如ipaddress、city-country等,所有这些数据都可以在location.php上获得。您现在可以将其保存在db中,或者您想用它执行的任何操作。以及为什么要将其传递到表单?然后为什么要发送pos到location.php??ajax将以隐藏的方式将值发送到location.php。您可以使用location.php上的查询将值保存在db中。
echo "position :=".$_POST['pos'];