如何使用某种类型的ajax将表单提交到另一台服务器上的页面?

Nat*_*han 1 forms jquery

我想将我的表单提交到另一个页面但是不要去那个页面(比如AJAX,但我知道AJAX不能跨域工作)

你们知道怎么做吗?我不喜欢将它提交到另一个网站上的页面,因为它实际上是一种更慢,更糟糕的做事方式.

谢谢,
内森约翰逊

Qua*_*unk 5

通过AJAX将您的表单提交到本地页面.您可以从该页面将数据发布到远程站点,例如cURL.

这是一个非常抽象的例子:

page_with_form.php

<form id="form1">
//input fields
</form>

<script>
$.post('post_to_remote.php', $('#form1').serialize(), function(){
   //do something when finished
   return false; //prevent from reloading 
});
</script>
Run Code Online (Sandbox Code Playgroud)

post_to_remote.php

  $param1 = $_POST['param1'];
  $param2 = $_POST['param2'];

  $remoteUrl = 'http://www.remote_site.com/page_to_post_to.php';
  $postFields = array('param1' => $param1, 'param2' => $param2);
  //if you don't want to do any sanitizing, you can also simply do this:
  //$postFields = $_POST;

  $data_from_remote_page = $getUrl($remoteUrl, 'post', $postFileds);

  function getUrl($url, $method='', $vars='') {
    $ch = curl_init();
    if ($method == 'post') {
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
    $buffer = curl_exec($ch);
    curl_close($ch);
    return $buffer;
  }
Run Code Online (Sandbox Code Playgroud)

如果你不需要curl的全部功能而且它只是一个简单的帖子,你也可以使用本机PHP函数:

$postFields = http_build_query($_POST);
$remoteUrl = 'http://www.remote_site.com/page_to_post_to.php';

$context = stream_context_create(
          array(
            'http' => array(
              'method' => 'POST',
              'header' => "Content-type: application/x-www-form-urlencoded\r\n",
              'content' => $postFields,
              'timeout' => 10,
            ),
          )
);

$result = file_get_contents($remoteURL, false, $context);
Run Code Online (Sandbox Code Playgroud)

一个不同的基本例子,但你明白了.