简体   繁体   中英

Create JSON object (with array) in php

I tried to create JSON object witch contain an array. I want to get JSON via AJAX, orginaly:

$.ajax({
    url: 'data/events.json',
    type: 'GET',
})

But I change this to

$.ajax({
  url: 'data/events.php',
  type: 'GET',
})

JSON I need looks like this:

{
  "events": [
  {
    "month": "6",
    "day": "12",
    "year": "2016",
    "title": "Lorem ipsum",
    "description": "desc..."
  },
  {
    "month": "6",
    "day": "9",
    "year": "2016",
    "title": "Lorem ipsum",
    "description": "desc..."
  }
  ]
}

I've tried:

$events = array(
    "events" => array(
        array(
            "month"=> "6",
            "day"=> "12",
            "year"=> "2016",
            "title"=> "Lorem ipsum",
            "description"=> "desc.."
        ),
        array(
            "month"=> "6",
            "day"=> "9",
            "year"=> "2016",
            "title"=> "Lorem ipsum",
            "description"=> "desc..."
        )
    )
);

echo json_encode($events);

But this is not working. Thank you in advance!

I think your array is ok , but in ajax
Try:

dataType: 'json' : This will convert your response to json object.

$.ajax({
    url: 'data/events.json',
    type: 'GET',
    dataType: 'json'
});

As the accepted answer didn't explain, I'll provide some information. In your original example, you have a static .json file, which when served by the webserver, will automaticllay be served with the application/json content type. However, in your php example, the webserver will not serve the JSON content type.

jQuery will automatically parse the response JSON if it detects the JSON content type. This is why your php example doesn't do exactly the same as the original, even though the JSON content itself is the same.

As Neeraj suggests, you can force the content type by setting dataType . Alternatively you can send the JSON header in your php, which will replicate your original example. It's good practice to set the relevant content type, so I recommend doing this even if you are setting dataType .

header('Content-Type: application/json');
echo json_encode($events);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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