2013-11-03 31 views
0

我使用此腳本根據帶有json響應的ajax請求更新表格單元格。它不會更新指定的表格單元格。我的json字符串格式不正確嗎?使用ajax json響應更新html元素

$(document).ready(function() { 

    $('select.swcomp').change(function() { 
     var res_id = $(this).val(); 
     var index = $(this).data('index'); 

     $.ajax({ 
      type: 'POST', 
      url:'http://skiweather.eu/v3/ajax/compare_snow.php', 
      data: '{ "res_id":"' + res_id + '", "index":"' + index + '" }', 
      contentType: 'application/json; charset=utf-8', 
      dataType: 'json', 
      success: function (response) { 
       $('#destin_' + index).html(response.resort);    
       $('#snowval_' + index).html(response.snow_valley); 
       $('#snowmnt_' + index).html(response.snow_mountain);    
      } 
     }); 
     return false; 
    }); 

}); 

HTML

<select name="resort_1" class="swcomp" data-index="1"> 
        <option value="NoResort">resorts</option> 
        <option value="6">Adelboden</option> 
        <option value="237">Davos</option> 
</select> 

<table> 
    <tr><td id="destin_1">res</td></tr> 
    <tr><td id="snowval_1">val</td></tr> 
    <tr><td id="snowmnt_1">mnt</td></tr> 
</table> 

JSON

var response =[{"snow_valley":"40","snow_mountain":"40","resort":"Adelboden"}] 

回答

2

響應不是一個對象,它是一個數組所以response.resort是不確定的應該是response[0].resort

$('#destin_' + index).html(response[0].resort);    
$('#snowval_' + index).html(response[0].snow_valley); 
$('#snowmnt_' + index).html(response[0].snow_mountain); 
+0

進行了更改,但仍不會更新表http://skiweather.eu/benchmark.php – mark

+0

您的ajax響應不正確...它是'var response = []'而不是'[{「snow_valley」:「40」,「snow_mountain」:「40」,「resort」:「Adelboden」}]' –

+0

我不明白你意思。 json字符串格式不正確? – mark

0

是你的收到的json格式正確。如果你想檢查你的json farmatted正確地按照這個網站http://jsonlint.com/它會檢查你的json驗證。訪問JSON數據http://jsontree.com/只需粘貼你的JSON並解析它將提供如何輕鬆訪問數據