编辑 在聊天中讨论了一些事情后,我们得出结论,服务器端发帖是一种更好的方式。下面是一个实现示例:
HTML:
<form id="my_form">
<!-- form elements -->
</form>
<div id="status_message"></div>
Javascript:
$('#my_form').on('submit', function (e){
$.ajax({
type: "POST",
url: "localProxy.php",
data: $('#my_form').serialize(),
success: function (response) {
// do something!
},
error: function () {
// handle error
}
});
});
PHP (localProxy.php)
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://thirdpartydomain.internet/login_url.php');
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $_POST);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);
curl_close($ch);
// do something with the data on your end (if anything), or render the "thank you" page
die('<h1>Thanks!</h1>');
原答案
有几种方法。
第一种方式,你(通过标签)提到你有 jQuery——在这种情况下,你可以使用 jquery 的 ajax 方法将数据发布到 API 和将其发送到您自己的服务器以获取感谢信息。
<form id="my_form">
<!-- form elements -->
</form>
<div id="status_message"></div>
...在您的“就绪”功能中:
var API_URL = 'http://www.some-api-provider.com/api.php';
var MY_URL = 'http://www.my-website.net/post_handler.php';
$('#my_form').on('submit', function (e){
e.preventDefault();
var error = false;
// validation here, if there is an error, set error = true;
if (error == true) {
alert('There was a problem!'); // do something better than this!
return false;
}
$.ajax({
type: 'GET',
url: API_URL,
data: $('my_form').serialize(),
success: function () {
$.ajax({
type: 'POST',
url: MY_URL,
data: $('#my_form').serialize(),
success: function (response) {
$('status_message').html(response);
},
error: function () {
alert('There was a problem!'); // do something better than this!
}
});
},
error: function () {
alert('There was a problem!'); // do something better than this!
}
});
return false;
});
那里发生了什么?我们使用on 事件将事件侦听器绑定到表单的“提交”事件。当用户单击提交按钮时,将调用该侦听器代码。
它会依次序列化表单的数据,然后通过 GET 将其发送到 API。只要它有效,它就会调用成功函数,该函数又会通过 POST 将数据发送到您的服务器。 div status_message 将使用服务器返回的结果进行更新。
另一种方法是将数据正常发布到您的服务器,然后使用 cURL 或其他一些服务器端 HTTP 连接将数据提交到 API。我可能会喜欢这种方法,因为它不太依赖于 javascript;如果您的用户关闭了脚本,则 javascript 方法将失败。
在不知道您使用的是什么服务器端技术的情况下,我无法举出任何示例,但如果您走这条路遇到麻烦,您可以随时提出另一个问题!
文档