2014-09-03 82 views
0

所以基本上,我試圖將一些數據發送到遠程PHP頁面,通過POST,有4個靜態參數和一個隨機參數,一個數字。 到目前爲止,我所做的是創建一個HTML頁面與4個隱藏字段和1個空場,其中隨機數是通過JavaScript(使用的Math.random)插入的值的形式。現在,每當我提出這種形式,它需要我到遠程PHP頁面,所以我要再次點擊返回(在瀏覽器中),然後提交。動態發送POST數據使用Javascript

所以,我決定在另一個HTML頁面的iFrame加載這種形式,所以點擊提交後,我就可以點擊刷新,然後再次提交。

我想知道,是有辦法,我可以使用JavaScript在父HTML自動提交表單中的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重新發送f orm多次,但mobile_no的值每次都不相同? 或者我可以通過簡單的Javascript(或PHP)簡單地發送帶有參數的POST數據到服務器:

回答

1

你的問題不是100%清楚,但它聽起來像你想異步張貼表單數據。您可以使用jQuery等JavaScript庫輕鬆完成此操作,而無需使用iframe。首先,您應該爲表單添加一個ID屬性,以便在jQuery代碼中進行引用。然後,您可以將一個事件監聽器附加到表單的提交事件,您可以在提交之前自定義表單並處理響應

$('#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 

     } 
    }); 
});