【发布时间】: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 $statusCode与exit;一样有用。所有执行都将在那里结束,不会向 HTTP 响应输出任何内容,因此您的 "nothing in the network panel" -
@DirtyBirdDesign 这不是有效的 JSON。你能链接到 API 文档吗?
-
@DirtyBirdDesign 我会说这只是一个文档错误。在 JSON 中,键和字符串值必须被引用