如何将 JSON 结果的值获取到标签中


How do I get the value of a JSON result into a label?

这是结果: [{"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);  
                }
            });
        });

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

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

此处的标签 ID 是 ParcelNumber 。要获取该值,您可能需要:

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

无论ParcelNumber不是"有价值的"控件(例如,不是input而是静态div),请使用.html方法:

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