【问题标题】:PHP Curl wont send POST requestPHP Curl 不会发送 POST 请求
【发布时间】:2014-11-06 03:35:59
【问题描述】:

我有一个 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"; 

【问题讨论】:

  • 您是否尝试过要发送到的 php 文件的绝对路径?即 - http://www.example.com/test.php
  • 我确实尝试过,但我得到了相同的结果(没有结果!)

标签: php ajax forms curl


【解决方案1】:

有几个问题,首先,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);

【讨论】:

  • @nadz 我的快乐伙伴,很高兴我能帮忙
猜你喜欢
  • 1970-01-01
  • 2016-03-08
  • 1970-01-01
  • 2012-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 2017-07-13
相关资源
最近更新 更多