【问题标题】:Sending data via jQuery Ajax as JSON to PHP Rest API with cURL通过 jQuery Ajax 将数据作为 JSON 发送到带有 cURL 的 PHP Rest API
【发布时间】:2019-04-15 17:08:04
【问题描述】:

我需要向 REST API 发送一些数据并包含自定义标头值。我尝试回显通过 cURL 脚本发送的数据,但我得到一个空白页。 这是我的 HTML

<form id="RestData" action=Processor.php" method="POST">
    <ul>
        <li>
            <input type="text" id="email" name="email">
        </li>
        <li>
            <input type="submit" value="Update User" id="">
        </li>
    </ul>
</form>

我的 jQuery:

$(function(){
    $('#RestData').validate({
        errorPlacement: function(error, element) {},
        submitHandler: function(form) {
            $.ajax({
                type:$('#RestData').attr('method'),
                url: form.action,
                data: {
                    email = $('#email').val();
                },
                beforeSend: function(data){
                    console.log(data);
                },
                success: function(data){
                    console.log(data);
                    if(data.type == "error") {
                        //error handling
                    } else if(data.type == "success"){
                        //success handling
                    } 
                }
            });
                return false;
        },
        rules: {
            email: {
                required:true,
                email:true
            }
        }
    });
});

此时,当我通过 PHP 处理器回显它时,我的 json 数组周围出现双引号

<?php
    $email = $_POST['email'];
    $expired = NULL;
    $funded = TRUE;

    $data = array(
        "email" => $email,
        "expired" => $expired,
        "funded" => $funded
    );
    echo json_encode($data);
?>

像这样 -> {"email":"test@test.com","expired":null,"funded":true} 我不知道这是否会成为问题,如果有必要,有什么想法可以删除吗?

使用我的最终 cURL 代码,什么都没有发生 - 空白屏幕,网络面板中没有任何响应。

<?php
    $email = $_POST['email'];
    $expired = NULL;
    $funded = TRUE;

    $data = array(
        "email" => $email,
        "expired" => $expired,
        "funded" => $funded
    );

    $url = 'https://rest.api';

    $json_string = json_encode($data);

    $headers = array (
        "Content-Type: application/json; charset=utf-8",
        "Content-Length: " .strlen($json_string),
        "Authorization: Bearer long token here"    
    );

    $channel = curl_init($url);
    curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($channel, CURLOPT_POSTFIELDS, $json_string);
    curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 10);

    curl_exec($channel);
    $statusCode = curl_getInfo($channel, CURLINFO_HTTP_CODE);
    curl_close($channel);    
    return $statusCode;
    echo $json_string;
?>

这有点超出我的驾驶室,我经常使用 cURL,只是不使用休息 API。我知道我应该得到回复,并试图在页面上回显它以进行调试,但我只是得到一个空白页面。

【问题讨论】:

  • 我不明白您关于 JSON 中引号字符的问题。您认为那里有什么问题?
  • 返回 $statusCode;回声 $json_string; //这个echo永远不会在return语句之后被调用。
  • 正如@Manpreet 所指出的,return $statusCodeexit; 一样有用。所有执行都将在那里结束,不会向 HTTP 响应输出任何内容,因此您的 "nothing in the network panel"
  • @DirtyBirdDesign 这不是有效的 JSON。你能链接到 API 文档吗?
  • @DirtyBirdDesign 我会说这只是一个文档错误。在 JSON 中,键和字符串值必须被引用

标签: php jquery json rest api


【解决方案1】:

您没有在变量中获得 cURL 响应。

其次,你在return语句之后做echo,它永远不会执行。

<?php
    $email = $_POST['email'];
    $expired = NULL;
    $funded = TRUE;

    $data = array(
        "email" => $email,
        "expired" => $expired,
        "funded" => $funded
    );

    $url = 'https://rest.api';

    $json_string = json_encode($data);

    $headers = array (
        "Content-Type: application/json; charset=utf-8",
        "Content-Length: " .strlen($json_string),
        "Authorization: Bearer long token here"    
    );

    $channel = curl_init($url);
    curl_setopt($channel, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($channel, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($channel, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($channel, CURLOPT_POSTFIELDS, $json_string);
    curl_setopt($channel, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($channel, CURLOPT_CONNECTTIMEOUT, 10);

    $response = curl_exec($channel);
    $statusCode = curl_getInfo($channel, CURLINFO_HTTP_CODE);
    curl_close($channel);

    http_response_code($statusCode);
    if ( $statusCode != 200 ){
       echo "Status code: {$statusCode} \n".curl_error($channel);
    } else {
       echo $response;
    }
?>

【讨论】:

  • 我会使用http_response_code() 将响应设置为远程服务的响应。这样 JS 端可以对 AJAX 调用使用正确的错误处理。
  • @Phil,谢谢。现在我得到“状态代码:500”。这可以与“授权”标题相关联吗?文档只是说“授权:承载(然后是一个很长的字符串)”?
  • @DirtyBirdDesign 我认为没有。这与内部服务器错误有关。你解决了吗?
  • 现在我得到状态码“0”,所以我相信 API 方面出了点问题。谢谢 Manpreet 和 @Phil 教我一些新东西!
  • 另外,上面的代码回显了$response,我没看到那个变量存在
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多