【问题标题】:Send JSON by cURL always returns "No access"通过 cURL 发送 JSON 总是返回“No access”
【发布时间】:2015-10-22 14:29:13
【问题描述】:

我有这个 JSON 数据:

$.ajax({
    type: "GET",
    url: "http://www.example.com/test.php",
    data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
    contentType: "application/json; charset=utf-8",
});

要将此数据发送到http://www.example.com/test.php,我已尝试使用此代码:

<?php

//API URL
$url = 'http://www.example.com/test.php';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = array(
    'data' => 'code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b'
);

//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);

//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);

//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

//Execute the request
$result = curl_exec($ch);

?>

但是,它总是返回No access

我的代码有什么问题?你能帮我解决它吗?


对不起,我的英语不好。如果我的问题不清楚,请在此问题下方评论。

【问题讨论】:

  • 有api信息的链接吗?
  • 这没什么。我说的是一个网页,它告诉你调用什么 URI 以及需要哪些字段等。
  • 那可能不是文档链接。
  • 代码没有问题。该文档将帮助我了解网站对数据和格式的期望。

标签: php jquery ajax json curl


【解决方案1】:

先查http://www.example.com/test.php

Ajax 系统不能与完整的域名一起使用。

所以你应该使用/test.php

然后检查您的站点或目标站点中发生的错误。

那么代码就变成了:

$.ajax({
    type: "GET",
    url: "/test.php",
    data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
    contentType: "application/json; charset=utf-8",
    success: function(data, textStatus) {   
        alert(data);
        data = $.parseJSON(data);
    },
    error : function(data, textStatus, error){                  
        alert(data + "  : "+ textStatus);
    }
});

【讨论】:

    【解决方案2】:

    如果没有查看文档,我唯一能建议的就是从数组中删除数据,并将其设为关键 code

    <?php
    
    //API URL
    $url = 'http://www.example.com/test.php';
    $data = "?code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b"
    
    //Initiate cURL.
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url . $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    //Execute the request
    $result = curl_exec($ch);
    
    ?>
    

    【讨论】:

    • 啊,我有点明白了。如果它是一个 GET 请求,您不需要这些选项的一半。您只需要将数据附加到 url 的末尾
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-18
    • 2012-11-13
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多