簡體   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