正确使用jQuery.Ajax脚本中JSON的返回值

时间:2011-11-03 10:13:48

标签: c# jquery asp.net json

我有2个DropDownList,就像Master-Slave一样。 这是我的Default.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
            <asp:Label ID="MsLbl" runat="server" Text="Groups" />
                </td>
                <td>
            <asp:DropDownList ID="Masterddl" runat="server">
                    <asp:ListItem Text="G1" Value="G1" />
                    <asp:ListItem Text="G2" Value="G2" />
                    <asp:ListItem Text="G3" Value="G3" />
            </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
            <asp:Label ID="Svlbl" runat="server" Text="Members" />
            </td>
                <td>
            <asp:DropDownList ID="Slaveddl" runat="server" />
            </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

这是我的剧本:

$(document).ready(function () {
$('select#Masterddl').change(function () {
    MasterChangeHandler($(this).val());
});

function MasterChangeHandler(Value) {
    $.ajax({
        type: 'Post',
        url: 'MasterSlaveHandler.ashx',
        dataType: "text",
        data: 'ItemSelected=' + Value,
        async: 'true',
        success: function (data) { SuccessHandler1(data); }

    });
}


function SuccessHandler1(data) {
    $('select#Slaveddl').empty();
    $.each(data, function (i, slaveValue) {
        $('select#Slaveddl').append(
    $('<option></option>').val(slaveValue.Value).html(slaveValue.Text)
    );
    });
}

我的处理程序:

public class SlaveValues {
    public string Value { get; set; }
    public string Text { get; set; }
}


public class MasterSlaveDropDownListsHandler : IHttpHandler {
    public bool IsReusable {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context) {
        string valueSelected = context.Request["ItemSelected"];
        List<SlaveValues> slaveValues = new List<SlaveValues>();
        SlaveValues sv;

        sv = new SlaveValues();
        sv.Text = "SV1";
        sv.Value = valueSelected + "s1";
        slaveValues.Add(sv);

        sv = new SlaveValues();
        sv.Text = "SV2";
        sv.Value = valueSelected + "s2";
        slaveValues.Add(sv);


        string responseText =
    Newtonsoft.Json.JsonConvert.SerializeObject(slaveValues);
        context.Response.ContentType = "text/json";
        context.Response.Write(responseText);
    }
}

但没有什么要追加的。 另外,我在firebug窗口中看到响应如下(当我从Master ddl中选择G2时):

[{"Value":"G2s1","Text":"SV1"},{"Value":"G2s2","Text":"SV2"}]

对于更具体的视图,当我在Master ddl中选择G3时,以下图片是firebug窗口中的JSON选项卡:

JSON tab in firebug window

我用这个新的脚本来改变我的成功脚本方法进行测试:

function SuccessHandler2(data) {
    $('select#Slaveddl').empty();
    $.each(data, function (i, slaveValue) {
        $('select#Slaveddl').append(
    $('<option></option>').val('Member' + i).html('Member' + i)
    );
    });
}

当尝试这个新脚本时,对Slave ddl的绑定正常工作但有一些额外的项目:索引显示member0到member30而我不知道为什么。

我也试试这个并正确追加:

function SuccessHandler3(data) {
var values = [{ "Value": "G2s1", "Text": "SV1" }, { "Value": "G2s2", "Text": "SV2"}];
        $('select#Slaveddl').empty();
        $.each(values, function (i, slaveValue) {
            $('select#Slaveddl').append(
$('<option></option>').val('Member' + slaveValue.Value).html('Member' +
 slaveValue.Text)
        );
        });
    }

所以我认为操纵返回值(数据)存在问题。

另外我尝试这个,只出现第一个警告,显然(data.d)是null或未知对象:

function SuccessHandler4(data) {
    var selection = $('select#Slaveddl');
    $(selection).children().remove();
    alert('in handler and remove children correctly');
    if (data.d) {
        alert('data.d is not null');
        $(data.d).each(function (index, item) {

$(selection).append('<option>').val(item.Value).html(item.Text);
            alert('after append in index: ' + index);
        });
    }
}

如何正确使用返回值并附加到Slave ddl?问题出在哪里?

修改

通过脚本和处理程序中的一些更改来查找它,如下所示:

脚本:

$(document).ready(function () {
$('select#Masterddl').change(function () {

    CallHandler();

});

function CallHandler() {
    $.ajax({
        url: "FinalRequest.ashx",
        contentType: "application/json; charset=utf-8",
        data: { 'ItemSelected': $('select#Masterddl').val(), 'ID':
  $('select#Masterddl').attr('id') },
        dataType: "json",
        responseType: "json",
        success: function (data) { SuccessHandler(data); },
        error: OnFail
    });
    return false;
}

function SuccessHandler(data) {
    $('select#Slaveddl').empty();
    $.each(data, function (i, slaveValue) {
        $('select#Slaveddl').append(
    $('<option></option>').val(slaveValue.Value).html(slaveValue.Text)
    );
    });
}

function OnFail(result) {
    alert('Request failed');

}

});

处理程序:

public class FinalMasterSlaveHandler : IHttpHandler {


    public bool IsReusable {
        get { return false; }
    }

    public void ProcessRequest(HttpContext context) {
        string valueSelected = context.Request["ItemSelected"];
        string IDSelected = context.Request["ID"];

        List<SlaveValues> slaveValues = new List<SlaveValues>();
        SlaveValues sv;

        sv = new SlaveValues();
        sv.Text = valueSelected + IDSelected + "T1";
        sv.Value = valueSelected + IDSelected + "V1";
        slaveValues.Add(sv);

        sv = new SlaveValues();
        sv.Text = valueSelected + IDSelected + "T2";
        sv.Value = valueSelected + IDSelected + "V2";
        slaveValues.Add(sv);

        JavaScriptSerializer javaScriptSerializer = new 
JavaScriptSerializer();
        string responseText = javaScriptSerializer.Serialize(slaveValues);

        context.Response.ContentType = "text/json";
        context.Response.Write(responseText);
    }



}

1 个答案:

答案 0 :(得分:0)

在您的代码的海洋中,我发现dataType: 'text'应为dataType: 'json'

请参阅jQuery.ajax(settings) documentation