【问题标题】:updating html elements with ajax json response使用 ajax json 响应更新 html 元素
【发布时间】:2013-11-03 08:52:53
【问题描述】:

我使用此脚本根据带有 json 响应的 ajax 请求更新表格单元格。它不会更新指定的表格单元格。我的 json 字符串格式不正确吗?

$(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"}]

【问题讨论】:

    标签: jquery ajax json


    【解决方案1】:

    response 不是一个对象,它是一个数组,所以 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); 
    

    【讨论】:

    • 进行了更改,但仍然没有更新表格skiweather.eu/benchmark.php
    • 您的 ajax 响应不正确...它是 var response =[] 而不是 [{"snow_valley":"40","snow_mountain":"40","resort":"Adelboden"}]
    • 我不明白你的意思。 json字符串格式不正确?
    • 我需要什么来改变 Arun?
    • @mark 回复应该是[{"snow_valley":"40","snow_mountain":"40","resort":"Adelboden"}] no var response = xxx
    【解决方案2】:

    是的,您收到的 json 格式正确。如果您想检查您的 json 农场是否正确,请关注此站点http://jsonlint.com/,它将检查您的 json 验证。用于访问 json 数据 http://jsontree.com/ 只需粘贴您的 json 并解析它将提供访问数据的容易程度

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 2012-05-05
      • 1970-01-01
      • 2019-01-12
      • 2021-03-26
      • 2013-10-31
      • 2017-10-31
      相关资源
      最近更新 更多