繁体   English   中英

通过POST从ajax调用到PHP页面获取JSON数据

[英]Get JSON data from ajax call to PHP page through POST

我想从一个表单中获取AJAX调用的一些数据。 我在PHP页面中将数据作为字符串获取。 字符串看起来像

'FNAME': 'ABC', 'L-NAME': '某某', '邮件': '', '通': '', '电话': '', '性别': '', '出生日期': ''

现在我想将整个字符串转换为数组,看起来像[“fname”] =>“abc”,[“lname”] =>“xyz”......依此类推

ajax调用如下:

fname = $("#form-fname").val();
lname = $("#form-lname").val();
email = $("#form-username").val();
pwd = $("#form-password").val();
phone = $("#form-phone").val();
gender = $("#form-gender").val();
dob = $("#form-dob").val();
var user = {"fname":fname,"lname":lname,"email":email,"pass":pwd,"phone":phone,"gender":gender,"dob":dob};
$.ajax({
      type: "POST",
      url: "doRegistration.php",
      data: user
 })
 .done(function( msg ) {                        
       window.location.href = "../profile.php";
 })
 .fail(function(msg) {
       sessionStorage.setItem("success","0");
       window.location.reload();
 }); 

这是我的PHP代码:

$content = file_get_contents("php://input");
file_put_contents("log1.txt",$content); //This produces the string I get above

现在我尝试将字符串转换为数组,如上所示

$dec = explode(",",$content);
$dec1 = array();
for($i=0;$i<count($dec);$i++)
{
    $dec1[i] = substr($dec[i],strpos($dec[i],":"));
}
//After this $dec1 is empty and count($dec1) gives 0.

但这并没有给我所需的数组。 我在这里查了几个答案,但它们没有解决我的问题。 我试图谷歌但没有找到任何解决方案。 代码中有什么问题吗? 请帮助。 提前致谢。

更改报价并添加大括号。 然后你可以解码生成的json

$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";

print_r(json_decode('{' . str_replace("'", '"', $string) . '}', true));

结果

Array
(
    [fname] => abc
    [lname] => xyz
    [email] => 
    [pass] => 
    [phone] => 
    [gender] => 
    [dob] => 
)

在上面的代码中,您使用for循环的索引作为数组的键。 如果您正在尝试存档(我相信它在Java中称为字典)。 您可以尝试以下代码:

<?php
$string = "'fname':'abc','lname':'xyz','email':'','pass':'','phone':'','gender':'','dob':''";
$pieces=explode(',',$string);
foreach($pieces as $array_format){
list($key,$value) = explode(':',$array_format);
$array[$key]=$value;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM