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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11030307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:52:12  来源:igfitidea点击:

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

phpjavascriptparsingform-submit

提问by sczdavos

I would like make a script using PHP (probably need JS) to send POST data to another webpage and get the result back.

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

For example, Domain A will have a form with a textbox and submit button, and Domain B will have a script which will fill the textbox and press the submit button and return the generated HTML page.

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

回答by ppsreejith

The following lines of code can be written on another php script,

下面几行代码可以写在另一个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);

Now $result will contain the text received from the other website.

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

回答by Bergi

With JS: for security reasons not. Read on Same origin policy.

用 JS:出于安全原因没有。阅读同源政策

With PHP you can do what you want, including POSTing other servers. For example use CURL.

使用 PHP,您可以为所欲为,包括使用POST其他服务器。例如使用CURL

回答by TimoSolo

--- Original 2012 Answer ---

--- 原始 2012 答案---

Use jquery; just load the page with a $.ajax() call. If you need to, you can use "jsonp" which works around the restrictions between calling pages from different domains.

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

The nice thing about using javascript is that you don't need any serverside languages.

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

--- 2018 edit ---

--- 2018 编辑 ---

I realise now that you can't do a POST with jsonp (as it is essentially read-only) so this will only work if the website accepts the form as a GET (ie, the parameters in the URL). Otherwise, best to use Curl or similar as suggested in other answers.

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