gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:24:36 24 4
gpt4 key购买 nike

我想将表单提交到另一个页面,但使其不转到该页面(如 AJAX,但我知道 AJAX 不能跨域工作)

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

谢谢,
内森·约翰逊

最佳答案

通过 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>

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;
}

如果您不需要curl的全部功能并且它实际上只是一个简单的帖子,您也可以使用 native 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);

一个不同的基本示例,但您明白了。

关于forms - 如何使用某种类型的ajax将表单提交到另一台服务器上的页面?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6978658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com