如何在外部网站上提交表单并获得生成的 HTML

How to submit form on an external website and get generated HTML?

本文关键字:HTML 表单 外部 网站 提交      更新时间:2023-09-26

我想使用PHP制作一个脚本(可能需要JS)将POST数据发送到另一个网页并返回结果。

例如,域 A 将有一个带有文本框和提交按钮的表单,域 B 将有一个脚本,该脚本将填充文本框并按提交按钮并返回生成的 HTML 页面。

以下代码行可以在另一个 php 脚本上编写,

//set POST variables
$url = 'the website from which you need data through post';
$fields = array(
            //post parameters to be sent to the other website
            'text'=>urlencode($_POST['text']), //the post request you send to this  script from your domain.
        );
//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));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);

现在$result将包含从其他网站收到的文本。

使用 JS:出于安全原因,不这样做。 阅读同源策略。

使用PHP,您可以做任何您想做的事情,包括POST其他服务器。例如,使用 CURL。

--- 2012 年原始答案---

使用 jquery;只需使用 $.ajax() 调用加载页面即可。如果需要,您可以使用"jsonp"来解决从不同域调用页面之间的限制。

使用javascript的好处是你不需要任何服务器端语言。

--- 2018年编辑---

我现在意识到你不能用jsonp做一个POST(因为它本质上是只读的),所以这只有在网站接受表单作为GET时才会起作用(即URL中的参数)。否则,最好使用 Curl 或其他答案中建议的类似方法。