2011-09-27 10 views
1

私は出力にこのPHPコードエコーnamestar_typeserviceによってjquery.each()が欲しいですが、エラーがあります。どのようにそれを修正ですか?JSONデータの後に予期しない非空白文字がありますか?

エラー:

An error has occured:
[object Object]
parsererror
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

私はこのPHPコードを持っている:

//$hotel_id = $this->input->post('hotel_id'); 
$hotel_id = array('1','2','3'); 
//print_r($hotel_id); 
foreach ($hotel_id as $val) { 
    $query_r = $this->db->query("SELECT * FROM hotel_submits WHERE id LIKE '$val' ORDER BY id desc"); 
    $data = array(); 
    foreach ($query_r->result() as $row) { 
     $data_s = json_decode($row->service, true); 
     $data_rp = json_decode($row->address, true); 
     $data[] = array(
      'name' => $row->name, 
      'star_type' => $row->star . '-' . $row->type, 
      'site' => $row->site, 
      'service' => $data_s, 
      'address' => $row->address 
     ); 
    } 
    echo json_encode($data); 
} 

これは、PHPコード上で出力されます:

[{ 
    "name": "how", 
    "star_type": "5-hotel", 
    "site": "www.sasaas.assa", 
    "service": ["shalo", "jikh", "gjhd", "saed", "saff", "fcds"]"address": "chara bia paeen" 
}][{ 
    "name": "hello", 
    "star_type": "4-motel", 
    "site": "www.sasasa.asas", 
    "service": ["koko", "sili", "solo", "lilo"]"address": "haminja kilo nab" 
}][{ 
    "name": "hi", 
    "star_type": "3-apparteman", 
    "site": "www.saassaas.aas", 
    "service": ["tv", "wan", "hamam", "kolas"], 
    "address": "ok" 
}] 

とエラーが出ます。この私のJSコード:

$.ajax({ 
    type: "POST", 
    dataType: "json", 
    url: 'get_residence', 
    data: dataString_h, 
    cache: false, 
    success: function (respond) { 
     //alert(respond); 
     $.each(respond[0].name, function (index, value) { 
      alert(value); 
     }); 
    }, 
    "error": function (x, y, z) { 
     alert("An error has occured:\n" + x + "\n" + y + "\n" + z); 
    } 
}); 

答えて

3

有効なjsonをエコーし​​ていません。これを試してみてください:

$hotel_data = array(); 
foreach(...) { 
    // .. do stuff 
    $hotel_data[] = $data; // add $data to the end of the $hotel_data array 
} 
echo json_encode(array('data' => $hotel_data)); 

これは配列にすべて$data配列をラップして、オブジェクトのデータ属性に入れます。次のようにして、JS側でこのデータにアクセスすることができます

$.each(response.data, function(i, obj) { 
    alert(obj.name); 
}); 

注:は、私は私が上に書いたPHPの構文についてはよく分からないです、私はPHPを書いて以来、しばらくして:)

1

あなたをPHPの出力は有効ではありませんjson、"address"の前にコンマが見つかりませんでした。

あなたはこのURLを使ってJSONを確認することができます。http://json.parser.online.fr/

1

あなたのJSONは完全に無効です。ループ内にjson-ecnoded配列をエコーし​​ないでください。

$all_data = array(); 
foreach ($hotel_id as $val) { 
    //..what you have there now, but instead if echo json_encode($data); you do 
    $all_data[] = $data; 
} 
//and finally 
echo json_encode('data'=>$all_data); 
関連する問題