簡體   English   中英

將字符串傳遞給AJAX / Json

[英]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);
            }
        }

    });

我將問題調試為:

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

亂搞亂糟糟的字符串?

您可能需要在序列化之前將值包裝在對象中,以便ASP.NET知道調用的值:

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

ASP.NET通常使用鍵名來確定將值賦給哪個參數(假設WebMethod的URL為index.aspx/s ):

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

此外,如果目標是集合,則data也可以是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

它需要一個對象參數,而不是一個字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM