[英]PHP Curl wont send POST request
我有一個html頁面,單擊一次按鈕即可通過ajax提交2個表單(formone和formtwo)。 將formone提交給formone.php,如果成功發送,則將formtwo提交給formtwo.php。 一切正常。 除非我需要通過POST將數據發送到另一個php腳本(在另一台服務器上,但是現在我正在同一台服務器上對其進行測試)。 我用以下代碼嘗試了它,但是它不起作用(盡管我沒有任何錯誤)。
我使用的卷曲代碼!
function transferData()
{
//Set up some vars
$url = 'test.php';
$user = 'sampletext';
$pw = 'sampletext';
$fields = array(
'user'=>urlencode($user),
'pw'=>urlencode($pw)
);
// Init. string
$fields_string = '';
// URL-ify stuff
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);
}
這是我的ajax表單提交的代碼:
function submitforms()
{
FormSubmissionOne();
function FormSubmissionOne()
{
//Form 1
var $form = $('#formone');
$.ajax(
{
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function (msg)
{
FormSubmissionTwo();
},
error: function(msg)
{
alert(msg);
}
});
}
function FormSubmissionTwo()
{
//Form 2
var $form2 = $('#formtwo');
$.ajax(
{
type: 'POST',
url: $form2.attr('action'),
data: $form2.serialize(),
success: function (msg)
{
alert(msg);
//redirection link
window.location = "test.php";
}
});
}
}
這是test.php(從curl函數接收腳本)
$one = $_POST['user'];
$two = $_POST['pw'];
echo "results:";
echo $one;
echo "\r\n";
echo $two;
echo "\r\n";
有幾個問題,首先, CURLOPT_POST
是boolean
而不是計數。
所以改變這個:
curl_setopt($ch,CURLOPT_POST,count($fields));
至
curl_setopt($ch,CURLOPT_POST, 1); // or true
其次,您需要告訴CURL您想要返回的數據。 您可以使用CURLOPT_RETURNTRANSFER
因此,與curl
相關的代碼應如下所示:
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
print_r($result); // just see if result
//close connection
curl_close($ch);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.