簡體   English   中英

提交表單值而不加載新頁面

[英]Submit form values without loading a new page

我有一種表格,我正在使用該表格將值傳遞到另一頁及其工作。

無論如何,沒有打開設置了表單操作的頁面就可以做到這一點?

我認為可以使用Ajax和javascript完成

echo "<form name=\"android\"  method=\"post\" action=\"http://www.example.com\" target=\"_blank\">";
echo "<input type=\"hidden\" name=\"appid\" value=\"$appid\" />";
echo "<input type=\"hidden\" name=\"pushmessage\" value=\"$pushmessage\" />";
echo "<input type=\"hidden\" name=\"username\" value=\"$user\" />";
echo "<input type=\"hidden\" name=\"pass\" value=\"$pass\" />";
echo  "<input type=\"hidden\" name=\"publisherid\" value=\"createcoolapps\" />";
//echo "<input type=\"submit\" value=\"Push\" name=\"sub\" />";
echo "</form>";
echo "<script> document.forms[0].submit();</script>";

嘗試這個:

$url = 'http://www.example.com/';
$fields = array(
    'appid' => urlencode($appid),
    'pushmessage' => urlencode($pushmessage),
    'username' => urlencode($user),
    'pass' => urlencode($institution),
    'publisherid' => urlencode("createcoolapps")
);

foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string, '&');

$ch = curl_init();

curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

$result = curl_exec($ch);

curl_close($ch);

是的,您可以使用Ajax完成此操作。 到目前為止,最簡單的方法是從以下位置使用jQuery的AJAX庫(因為如果沒有別的,誰現在使用jQuery): http : //api.jquery.com/jQuery.ajax/

示例如下(未經測試,但有些正確):

<form action="mypage.php" method="post"> <!-- Args for when JS is disabled -->
    <input type="text" id="form_text_1" value="" />
    <input type="submit" id="form_submit" />
</form>

<script>
    $('#form_submit').click(function() {
        jquery.ajax("mypage.php", {
            type: "post",
            data: {
                text1: $('#form_text_1').val()
            }
        });
        return false; // Stop the form being submitted in the foreground when JS works
    });
</script>

當然,請根據您的需求進行調整。

如果您可以包含jQuery庫,則這非常容易: http : //www.jquery.com

如果使用jQuery和上面的代碼,則可以執行以下操作:

$('input[name="sub"]').click( function() {
   $.post($(this).parents('form').attr('action'), $(this).parents('form).serialize());
   return false;
} );

這攔截了名為“ sub”的提交的單擊,然后執行並將AJAX發布到表單的動作。

您最好查看瀏覽器控制台,以跟蹤發布的數據並發現任何問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM