簡體   English   中英

提交外部表單,而無需離開頁面/站點

[英]Submit external form without leaving the page/site

我在網站上尋找了答案,但是沒有找到我所需要的內容(這很接近,只不過它實際上沒有提交表單: 阻止表單重定向或刷新提交? )。

我正在嘗試將郵件列表注冊(從ReverbNation托管的注冊頁面借來的代碼)並入網站。

表單可以正確提交,但是簽署人將被重定向到ReverbNation網站上一個丑陋的頁面。 我不能修改他們的腳本,也不認為可以使用API​​來保持整潔。

有沒有一種方法可以在后台提交表單而無需重定向用戶?

如果要發布到同一域,則可以使用AJAX發布。 但是,您似乎正在嘗試將其發布到其他域,因此瀏覽器的相同來源策略將阻止您這樣做(http://en.wikipedia.org/wiki/Same_origin_policy)。 (JSONP可以解決此問題,但不適用於POST)

解決此問題的另一種方法是讓服務器執行POST並將響應傳送回您的頁面。

<form id='yourForm' action="" onsubmit="javascript: doPostToTunnelPage(); return false;">
    <!-- inputs...-->
</form>

確保返回false,否則頁面將被重定向。

這是PHP中用於傳送POST的示例。

//set POST variables
$url = 'http://domain.com/url-to-post-to';
$fields = array(
            // Add the fields you want to pass through
            // Remove stripslashes if get_magic_quotes_gpc() returns 0.
            'last_name'=>urlencode(stripslashes($_POST['last_name'])),
            'first_name'=>urlencode(stripslashes($_POST['first_name'])),
            'email'=>urlencode(stripslashes($_POST['email']))
        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));

// returns the response as a string instead of printing it
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

//execute post
$result = curl_exec($ch);

//close connection
curl_close($ch);

echo $result;

據我了解,您需要發送不帶重定向的表格嗎?

考慮我的例子

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

        $.ajax({ /* params to send the form */ });

        return false;
    });
});

IIT它將僅由於e.preventDefault而工作。

If this method is called, the default action of the event will not be triggered. 

見jQuery的文檔在這里獲取更多信息。

希望對你有幫助

暫無
暫無

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

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