简体   繁体   中英

Passing a string to AJAX/Json

function s() {
    data = "192,273,182,347,13,34,52,2524";
    var jsondata = $.toJSON(data);
    $.ajax({
        type: "POST",
        url: "index.aspx/s",
        data: jsondata,
        contentType: "application/json; charset=utf-8",
        dataType: "text json",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Content-type",
                         "application/json; charset=utf-8");
        },
        success: function (msg) {
            if (msg.d == "OK") {
                //WIN!
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (typeof (errorThown) != "undefined")
                alert("ERROR: SaveWidgetSettings() " + textStatus + '\n' + errorThrown);
            else {
                var errdetail = eval("(" + XMLHttpRequest.responseText + ")");
                alert("ERROR: SaveWidgetSettings() " + textStatus + '\n' + errdetail.Message);
            }
        }

    });

I debugged the issue to:

cannot convert object of type 'system.string' to type 'system.collections.generic.idictionary 2 system.string system.object '

are the commas messing up the string?

You may need to wrap the value in an object before serializing so ASP.NET knows what the value is called:

data = { csv: "192,273,182,347,13,34,52,2524" };

ASP.NET often uses key names to determine which argument to assign a value to (assuming WebMethod with the URL being index.aspx/s ):

[WebMethod]
public static object s(string csv) ...

Also, if the goal is a collection, data can also be an Array :

data = { ids: [192, 273, 182, 347, 13, 34, 52, 2524] };

// then...
[WebMethod]
public static object s(IEnumerable<int> ids) ...
data = "192,273,182,347,13,34,52,2524";
var jsondata = $.toJSON(data);

http://www.jquerysdk.com/api/jQuery.toJSON

It takes an object argument, not a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM