繁体   English   中英

使用Javascript发送动态POST数据

[英]Sending dynamic POST data with Javascript

所以基本上,我试图通过POST将一些数据发送到远程PHP页面,其中包含4个静态参数和一个随机参数(一个数字)。 到目前为止,我所做的是创建了一个HTML页面,该页面的表单包含4个隐藏字段和1个空字段,其中通过Javascript(使用Math.random)将一个随机数作为值插入。 现在,每当我提交此表单时,它将带我到远程PHP页面,因此,我必须再次单击返回(在浏览器中),然后提交。

因此,我决定将此表单加载到另一个HTML页面的iFrame中,因此在单击“提交”后,我可以单击“刷新”,然后再次提交。

我想知道,有没有一种方法可以在父HTML中使用Javascript在iFrame中自动提交表单,然后创建一个新的随机值并再次提交?

到目前为止,这是我的代码

a.html

<html>
<body>
<form method="post" action="http://awebsite.com/remotefile.php">
*some hidden fields with the static values*
<input type="text" id="mytext" name="mobile_no">
<input type="submit">
</form>
<script>//don't remember the exact code, use javascript to generate a random number which is put in the value for mytext via getElementById</script>
</body>
</html>

现在这是手动将数据发送到服务器的形式

这是要加载iframe:b.html

<html>
<body>
<iframe src="a.html">
</body>
</html>

我可以在b.html中使用javascript多次重新发送表单,但每次的mobile_no值都不同吗? 或者我可以简单地通过简单的Javascript(或PHP)将带有参数的POST数据发送到服务器

您的问题不是100%清楚,但听起来您想异步发布表单数据。 您可以使用jQuery之类的JavaScript库轻松完成此操作,而无需iframe。 首先,您应该在表单中添加一个ID属性,以使其更易于在jQuery代码中引用。 然后,您可以将事件侦听器附加到表单的Submit事件,在提交事件之前可以自定义表单并处理响应

$('#myForm').submit(function(e) {

    // prevent default form submit action from occuring
    e.preventDefault();

    // load values need to make AJAX request
    var method = $(this).attr('method');
    var action = $(this).attr('action');

    // Process Ajax request
    $.ajax({
        type: method,
        url: action,
        dataType: 'html',
        data: $(this).serialize(),
        beforeSend: function() {

            // generate and assign per form submit random number
            // show loading gif

        },
        success: function(response) {

            // AJAX POST success, insert the HTML response into the DOM

        },
        error: function(jqXHR, textStatus, errorThrown) {

            // console.log any errors for debugging here

        },
        complete: function() {

            // Post completion tasks, such as hide loading gif

        }
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM