用ajax json响应更新html元素 [英] updating html elements with ajax json response

查看:68
本文介绍了用ajax json响应更新html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use this script to update table cells based on ajax request with json response. The thing it does not update the specified table cells. Is my json string not formatted correctly?

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

推荐答案

响应不是对象,而是数组,因此未定义response.resort,应为response[0].resort

response is not an object, it is an array so response.resort is undefined it should be response[0].resort

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

这篇关于用ajax json响应更新html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆