Ajax return multiple values

左心房为你撑大大i 提交于 2019-12-11 18:29:17

问题


I'm trying to return multiple values as shown below but one value is only returning on success.

This is what I'm trying to do :

<script type="text/javascript">
        $(document).ready(function () {
                $("#getdetails").click(function () {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/Gettext",
                    data: JSON.stringify({ SampleText: $('#sampletext').val(), FontType: $('#fonttype').val()}),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        $("#Result").text(msg.d);
                    }
                });

        $("#FontLists").change(function () {
            $('#fonttype').val($('#FontLists option:selected').text());
        });
    });
</Script>

HTML:

Enter Text :<input id="sampletext" type="text" />
<select id="FontLists">
    <option value="Aharoni">Aharoni</option>
    <option value="Algerian">Algerian</option>
    <option value="Andalus">Andalus</option>
</select>
<input id="fonttype" type="hidden" />

Codebehind:

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Function Gettext(ByVal SampleText As String, ByVal FontType As String) As String
    Return SampleText
    Return FontType
End Function

回答1:


You could design a class with 2 properties and then have your WebMethod return an instance of this class (sorry if I made some typos, my VB.NET skills are rusty).

Public Class MyModel
    Public Property SampleText as String
    Public Property FontType as FontType
End Class

and then adapt your method to return this model:

<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Shared Function Gettext(ByVal SampleText As String, ByVal FontType As String) As MyModel
    Dim model = New MyModel()
    model.SampleText = SampleText
    model.FontType = FontType
    Return model
End Function

and on the client you could access the 2 properties using their names:

success: function (msg) {
    alert(msg.d.SampleText);
    alert(msg.d.FontType);
}


来源:https://stackoverflow.com/questions/14796266/ajax-return-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!