我试图将此字符串发送到php文件并将其转换回去。
$htmlparts= '{"footer.html" : "<div id="footer" class="tpl_area edtr_element" contenteditable="true"><footer class="container" id="1194">...</footer></div>","page_index.html" : "<div id="pagecontent" class="tpl_area edtr_element" contenteditable="true">...</div>","header.html" : "<div id="header" class="tpl_area edtr_element" contenteditable="true"><header id="1094"><nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark" data-editor-id="1095" id="1095">... </nav>
</header></div>" }';
使用以下方法来调用ajax:
data={'htmlparts': htmlparts, ...somethings more...}
$.ajax({
url: url,
method: 'POST',
data: data,
dataType:'json',
...
在控制台中,我看到正确调用了“ htmlparts”:
在php(codeigniter项目)中,我试图获取此内容
$test=json_decode($_POST['htmlparts']);
echo"<pre>";
print_r($test);
echo"<pre>";
但结果是我什么也没得到(只有<pre></pre>
)
我做错了什么?
答案 0 :(得分:0)
您需要将json对象调整为以下格式:
class Captcha{
public function getCaptcha($SecretKey){
if($SecretKey){
// Input data
$secret = 'SECRET_KEY';
$response = $SecretKey;
$remoteip = $_SERVER['REMOTE_ADDR'];
$url = "https://www.google.com/recaptcha/api/siteverify";
$post_data = http_build_query(
array(
'secret' => $secret,
'response' => $response,
'remoteip' => $remoteip
)
);
$options=array(
// If site has SSL then
'ssl'=>array(
// In my case its /etc/ssl/certs/cacert.pem
'cafile' => '/path/to/cacert.pem',
'verify_peer' => true,
'verify_peer_name' => true,
),
'http' =>array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
$context = stream_context_create( $options );
$Resposta = file_get_contents( $url, false, $context );
$Retorno = json_decode($Resposta);
return $Retorno;
}
}
public function returnCaptcha(){
echo "entrou calss_captcha";
$EnviaMail = False;
$ObjCaptcha = new Captcha();
$Retorno=$ObjCaptcha->getCaptcha($_POST['g-recaptcha-response']);
var_dump($Retorno);
if($Retorno->success == true && $Retorno->score > 0.5){
$EnviaMail = True;
}else{
$EnviaMail = False;
}
return $EnviaMail;
}
}
还需要对此对象进行字符串化。
答案 1 :(得分:0)
$_POST
在您的情况下将为空数组。尝试使用此
$decoded = json_decode(trim(file_get_contents("php://input")), true);
$decoded
将包含从前端接收到的已解析的JSON。
答案 2 :(得分:0)
要在您的json
请求中发送ajax post
,您的请求需要contentType
,并且数据应编码为json
,例如:
data={'htmlparts': htmlparts, ...somethings more...}
$.ajax({
url: url,
method: 'POST',
// notice the changes here
contentType: 'application/json'
data: JSON.stringify(data),
...