2011-09-27 68 views
1

我想在輸出這個PHP代碼回聲name,star_type,servicejquery.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

你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); 
相關問題