首页 > 解决方案 > 如何从php返回json数据

问题描述

我需要返回geojson数据以响应 ajax 请求。

这是我的 ajax 代码:

$.ajax({
    url : 'database_query.php',               
    data:'begin='+$("#begin").val(),
    type : 'GET',
    dataType : 'json',
    success : function(code_json, statut){
        alert("success" +" "+code_json+" "+statut)
    },
    error : function(resultat, statut, erreur){
        alert(erreur)
    }
});

这是database_query.php由 ajax 触发的 php 文件:

<?php
try{
    // On se connecte à MySQL

    $bdd = new PDO('mysql:host=localhost;dbname=nyc;charset=utf8', 'root', '');
} catch(Exception $e) {
    // En cas d'erreur, on affiche un message et on arrête tout
    die('Erreur : '.$e->getMessage());
}
if(isset($_GET["begin"])){
    $data={"features": [{"geometry": {"coordinates": [-73.95240784, 40.81072617], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.96302032, 40.71183395], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.84346008, 40.75595093], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.92481232, 40.75424576], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.92950439, 40.75645065], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.9250412, 40.76170349], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.90320587, 40.74570465], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.84425354, 40.72134018], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.98892975, 40.70240021], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.95552826, 40.8044548], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.95846558, 40.71715546], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.9287262, 40.75831223], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.90457916, 40.74129486], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.94830322, 40.80869675], "type": "Point"}, "properties": {}, "type": "Feature"}, {"geometry": {"coordinates": [-73.93263245, 40.8042717], "type": "Point"}, "properties": {}, "type": "Feature"}], "type": "FeatureCollection"}
    echo $data;
}

?>

我得到的错误是:

 SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"

我错过了什么或弄错了什么?

标签: phpajax

解决方案


要返回 json 作为响应,不要手动创建它,而是创建一个普通的 php 数组并执行

echo json_encode($data);

将 json 返回到您的 ajax 调用


推荐阅读