【问题标题】:How to submit form on an external website and get generated HTML?如何在外部网站上提交表单并获取生成的 HTML?
【发布时间】:2012-06-14 09:32:02
【问题描述】:

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

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

【问题讨论】:

  • 使用 JS:您可能可以将表单发布到另一个网站,但您无法获得生成的 HTML。您需要一个服务器端表单提交代理。
  • 好的。有没有可能我只能发布表格?
  • @sczdavos 你在使用像 jquery 或原型这样的 JavaScript 库吗?
  • @ryacii 感谢您的回复我已经使用了 ppsreejith 的解决方案

标签: php javascript parsing form-submit


【解决方案1】:

以下几行代码可以写在另一个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 将包含从其他网站收到的文本。

【讨论】:

  • 当我输入时出现错误:注意:未定义索引:第 6 行 C:\xampp\htdocs\proxy\test.php 中的 hello 注意:未定义变量:C:\xampp 中的字段字符串第 10 行的 \htdocs\proxy\test.php 帮助?
【解决方案2】:

使用 JS:出于安全原因不使用。继续阅读Same origin policy

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

【讨论】:

    【解决方案3】:

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

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

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

    --- 2018 年编辑 ---

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 2017-11-05
      • 2012-02-03
      • 1970-01-01
      相关资源
      最近更新 更多