1

您好我有一个以 json 格式返回数据的 Web 服务。我无法绑定从 Web 服务返回的国家名称和国家代码。我的代码是


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<title>Using jQuery and XML to populate a drop-down box demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax({
            type: "get",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({"objectData": formData}),
            url: "127.0.0.1:15021/Service1.svc/getallcustomers",
            dataType: "json",
            success: ajaxSucceess,
            error: function(xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(xhr.responseText);
                alert(thrownError);
            }
            //error: ajaxError
        });

        function ajaxSucceess(response) {
            $.each(response.d, function(key, value) {
                $("#ddlCountry").append($("<option>       </option>").val(value.country_code).html(value.country_name));
            });
        }
        function ajaxError(response) {
            alert(response.status + ' ' + response.statusText);
        }
    });
</script>

我的html代码是

<body> 
    <div>
        <select id="ddlCountry"> 
            <option value="-1">loading</option> 
        </select>
    </div>
</body>
</html>

从 Web 服务返回的示例 json 数据

// 正确的json格式

{
    "GetAllCustomersResult": [
        {
            "country_code": "OT",
            "country_desc": "Other",
            "country_name": "Other",
            "country_sk": "-1",
            "country_telecom_code": "+1",
            "currency_sk": 225,
            "date_format": "mdy",
            "distance_measurement_unit": null,
            "fnb_type_sk": "",
            "is_sms_notification": null
        },
        {
            "country_code": "ZW",
            "country_desc": null,
            "country_name": "Zimbabwe",
            "country_sk": 239,
            "country_telecom_code": "263",
            "currency_sk": 11,
            "date_format": null,
            "distance_measurement_unit": null,
            "fnb_type_sk": "",
            "is_sms_notification": null
        }
    ]
}
4

4 回答 4

1

您需要在以正确格式附加到选择框时推送值。

    <title>Using jQuery and XML to populate a drop-down box demo</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {
    $.ajax({
    type: "get",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ "objectData": formData}),
    url: "127.0.0.1:15021/Service1.svc/getallcustomers",
    dataType: "json",
    success: ajaxSucceess,
    error: function (xhr, ajaxOptions, thrownError) {
               alert(xhr.status);
               alert(xhr.responseText);
               alert(thrownError);
           }
    //error: ajaxError
    });

    function ajaxSucceess(response) {
    $.each(response.d, function (key, value) {
//Assuming key is the country code and value is country name in the this function.
appendString= "<option value='"+key+"'>"+value+"</option>";
    $("#ddlCountry").append(appendString);
    });
    }
    function ajaxError(response) {
    alert(response.status + ' ' + response.statusText);
    }
    });
    </script>

编辑的代码:这是一个经过测试的工作代码

    $(document).ready(function () {
        response = '{"GetAllCustomersResult":[{"country_code":"OT","country_desc":"Other","country_name":"Other","country_sk":-1,"country_telecom_code":"+1","currency_sk":225,"date_format":"mdy","distance_measurement_unit":null,"fnb_type_sk":"","is_sms_notification":null},{"country_code":"ZW","country_desc":null,"country_name":"Zimbabwe","country_sk":239,"country_telecom_code":"263   ","currency_sk":11,"date_format":null,"distance_measurement_unit":null,"fnb_type_sk":"","is_sms_notification":null}]}';
    ajaxSucceess(response);
    });

function ajaxSucceess(response) {

  responseJSON = $.parseJSON(response);
        console.log(responseJSON);
    $.each(responseJSON, function (key, value) {
        currentObj = $(this);
        $.each(currentObj,function(key,value)
               {
                   console.log(value);
                   country_code = value.country_code;
                   country_name = value.country_name;
                   appendString = "<option value='"+country_code+"'>"+country_name+"</option>";
                   $("#ddlCountry").append(appendString);
               });
//Assuming key is the country code and value is country name in the this function.

    });
    }
    function ajaxError(response) {
    alert(response.status + ' ' + response.statusText);
    }
于 2013-06-06T06:04:04.623 回答
0

尝试创建没有结束标签的选项。JQuery 会将其评估为 DOM 元素

$('<option />').val('Your value').html('html inside');

chrome 开发者工具中的快速测试

var a = $('<option />').val('a').html('the a');
$('<select />').append(a);

将值附加到选择标记中。

UPD:您是否尝试过查看开发人员控制台中的键和值?您可能在解析结果时出错。下断点,分析结果。

于 2013-06-06T06:18:10.277 回答
0

这可能会帮助你。

function ajaxSucceess(response) {
    var options = "";
    $.each(response.d, function (key, value) {
        options+= '<option vlaue="'+value.country_code+'">'+value.country_name+'</option>';
    });
    $("#ddlCountry").html(options);
}
于 2013-06-06T06:08:28.980 回答
0

在 ajax 中尝试将 jsonp 作为 dataType:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {$.ajax({
        type: "get",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({"objectData": 'formDataText'}),
        url: "http://doctor2book.com/service1.svc/getallcountries?callback=?",
        jsonpCallback: 'callbackParseJSON',
        crossDomain: true,
        dataType: "jsonp",
        success: successResponse,
        error: errorResponse
});// end ajax

// callback function form web services json data
function callbackParseJSON(response){
    alert('Callback Function called.');
}
// success function
function successResponse(response){
// get response data from web services
alert('Success!!');
// parse json data from web services
$.each(response.GetAllCustomersResult, function (key, value) {
    var appendData = "<option value='" + value.country_code + "'>" + value.country_name + "</option>";
    $("#ddlCountry").html($("#ddlCountry").html() + appendData);
});
}

// ajax error function
function errorResponse(xhr, ajaxOptions, thrownError) {
    alert('Error on Ajax Call' + '\n Status: ' + xhr.status + '\n Response Text: ' + xhr.responseText + '\n Error: ' + thrownError);                
}

});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JSONP Demo</title>
</head>

<body>    
        <select id="ddlCountry"> 
            <option value="-1">loading</option> 
        </select>          
</body>
</html>
于 2013-06-06T06:29:11.690 回答