【问题标题】:Posting JSON to php and then curling to different domain将 JSON 发布到 php,然后卷曲到不同的域
【发布时间】:2014-03-26 10:25:40
【问题描述】:

我想要实现的目标:使用 HTML/JQUERY 并将 XMLHttpRequest (JSON) 发布到 php 文件中,然后我们可以使用 CURL 将 json 提交到外部网站。

这是我提交数据的方式:

var myDate = "30/01/2014";
var n=myDate.split("/");
var fdate = (n[2]+"-"+n[1]+"-"+n[0] );

var xhr = new XMLHttpRequest();
xhr.open("POST", "index.php");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
  if (this.readyState == 4) {
    alert('Status: '+this.status+'\nHeaders: '+JSON.stringify(this.getAllResponseHeaders())+'\nBody: '+this.responseText);
  }
};
xhr.send("{\n    \"utoken\":  \"\",,\n    \"email\": \"blah@blah.co.uk\",\n    \"customer_name\": \"blah blah\",\n    \"order_id\": \"112897\",\n    \"platform\": \"general\",\n    \"order_date\": \"" + fdate + "\",\n    \"currency_iso\": \"GBP\"\n}");

现在我如何在 php 中获取这些数据并对其进行操作。因为有类似utoken 之类的东西,我可以从 php 文件中获取,但无法获取其他信息。

PHP

$chs = curl_init();
curl_setopt($chs, CURLOPT_URL, "EXTERNAL API URL");
curl_setopt($chs, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($chs, CURLOPT_HEADER, FALSE);
curl_setopt($chs, CURLOPT_POST, TRUE);
curl_setopt($chs, CURLOPT_POSTFIELDS, print_r($HTTP_RAW_POST_DATA););
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response = curl_exec($chs);
curl_close($chs);

【问题讨论】:

  • 你熟悉PHP中的json_decode吗?

标签: javascript php jquery json curl


【解决方案1】:

你应该像这样格式化你想要发送的数据:

xhr.send("utoken=&email=blah@blah.co.uk&customer_name=blah blah&order_id=112897&platform=general&order_date=" + fdate + "&currency_iso=GBP");

以下行也不起作用,因为 print_r 打印出一个数组。您还有语法错误(函数参数中的;)。

curl_setopt($chs, CURLOPT_POSTFIELDS, print_r($HTTP_RAW_POST_DATA););

改为尝试:

curl_setopt($chs, CURLOPT_POSTFIELDS, $HTTP_RAW_POST_DATA);

希望有帮助

【讨论】:

    【解决方案2】:

    由于您发帖JSON,您的发帖请求应如下所示:

    curl_setopt($chs, CURLOPT_POSTFIELDS, '{"utoken":"", "email":"some@xya.xom"}');
    

    或者,如果您有一个如下所示的数组,那么您可以使用json_encode 将您的数组轻松转换为json 以供发布。

    $post_data = array(
        "utoken" => "",
        "email" => "some@xya.com"
    );
    curl_setopt($chs, CURLOPT_POSTFIELDS, json_encode($post_data));
    

    仅供参考:函数json_encode 将数组值转换为{"utoken":"","email":"some@xya.com"}

    【讨论】:

      猜你喜欢
      • 2017-04-09
      • 1970-01-01
      • 2016-05-17
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      相关资源
      最近更新 更多