json_encode返回null php数组

时间:2015-09-06 05:55:53

标签: php ajax json

我正在尝试将一个php数组发送到ajax,但它不起作用。说实话,我不知道我做错了什么。

我正在使用返回null的json_encode()。

我的PHP代码:

$arr['worldpopulation']= $emparray[];
$fp = fopen('jsonparsetutorial.txt', "w");
fwrite($fp, json_encode($arr));
fclose($fp); ?>

我的ajax代码:

$info = array();
$info['NEW YORK CITY'] = array(
'Name' => 'New York City'
);

$city = $_POST['city'];

if (strtoupper($city) === 'NEW YORK CITY') {

echo "Name: " . json_encode($info['NEW YORK CITY']['Name']) . ".<br>";
} else {
echo "error.";
}

修正了它!我在数组之前有json_encode。现在我将数组放在最上面了。

3 个答案:

答案 0 :(得分:0)

json_encode接受数组作为参数

这将采取以下

array('key' => 'value')

这将以正确格式化的json key:value发送。但是单个值将无法正确处理,并可能导致不必要的结果。

答案 1 :(得分:0)

用以下

替换您的PHP代码
$city = $_POST['city'];
 if (strtoupper($city) === 'NEW YORK CITY') {
     echo json_encode($info['NEW YORK CITY']);
 } else {
     echo json_encode(array("error."));
 }

答案 2 :(得分:0)

如果有效,请尝试此操作:

  $city = $_POST['city'];

   if (strtoupper($city) === 'NEW YORK CITY') {
    echo json_encode(['Name' => $info['NEW YORK CITY']['Name'] ]);
   } else {
     echo json_encode(['error']);
   }

的Ajax:

 $('form.ajax').on('submit', function() {
  var that = $(this),
  url = that.attr('action'),
  type = that.attr('method'),
  data = {};

  that.find('[name]').each(function(index, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();

        data[name] = value;

   $.ajax({
    url: url,
    type: type,
    data: data,
    success: function(response) {
        //console.log(response);

        $('form.ajax').html(response);
     }
     }).fail(function(jqXHR) {
     alert(jqXHR.statusText);
   });

    return false;

  });

});

你的ajax应该在提交之后然后它将触发AJAX函数。

相关问题