如何将JSON结果的值转换为标签?

时间:2014-12-01 15:32:55

标签: php jquery ajax

结果如下:[{“apn”:“173-76-001”}]

从这段代码(php):

<?php
require_once('../config.php');

if(isset($_GET['parcel_id'])) {
    $db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
    $data = $db->get_results("select apn from parcels where parcel_id=" . $_GET['parcel_id']);
    if($data != null) echo json_encode($data);
    //if ($data != null) echo $data;
}
?>

jquery的:

        $('#searchTable tr').click(function(){
            var parcel_id = $(this).attr('id');
            alert(parcel_id);
            $.ajax({
                url: "classes/get-apn.php?id=" + parcel_id,
                //timeout: 30000,
                type: "GET",
                error: function(SMLHttpRequest, textStatus, errorThrown){
                    alert("An error has occurred making the request: " + errorThrown);
                },
                success: function(data){
                    //do stuff here on success
                    alert(data);
                    $('#ParcelNumber').val(data);               
                }
            });
        });

如何将apn(173-76-001)的值加入标签?

我是最新的,所以感谢你的帮助! :)

编辑:所以我尝试了下面的回复,但它没有用。我被告知我需要使用jQuery.parsJSON进行解析,但它也无法正常工作。我很困惑。这是我更新的jQuery代码:

        $('#searchTable tr').click(function(){
            var parcel_id = $(this).attr('id');
            $('#ParcelId').html(parcel_id);
            $.ajax({
                url: "classes/get-apn.php?id=" + parcel_id,
                //timeout: 30000,
                type: "GET",
                data: { parcel_id : parcel_id },
                dataType: 'json',
                error: function(SMLHttpRequest, textStatus, errorThrown){
                    alert("An error has occurred making the request: " + errorThrown);
                },
                success: function(data){
                    //do stuff here on success
                    var result = $.parseJSON(data);
                    alert(result.apn);  
                }
            });
        });

1 个答案:

答案 0 :(得分:1)

您对服务器执行ajax请求。服务器查询数据库并将输出格式化为json。 Ajax请求由此成功,以下代码行设置标签的值:

$('#ParcelNumber').val(data); 

此处的标签ID为ParcelNumber。要获得您可能需要的价值:

$('#ParcelNumber').val(data[0]["apn"]); 

ParcelNumber是否不是“有价值”控制(例如,不是input而是静态div),请使用.html方法:

$('#ParcelNumber').html(data[0]["apn"]);