简体   繁体   English

Javascript和C#处理程序-带有JSON的AJAX,发送数组

[英]Javascript and C# Handler - AJAX with JSON, sending array

When I send an array with AJAX (using JSON), my C# handler does not know how to handle the whole query (suddenly the querystrings combine with each other for some reason). 当我使用AJAX发送数组(使用JSON)时,我的C#处理程序不知道如何处理整个查询(由于某种原因,查询字符串突然合并在一起)。

In this example I'm sending a very simple array to the server and the server says the querystring Name is null (but it is not null); 在此示例中,我向服务器发送了一个非常简单的数组,服务器说querystring Name为null(但不为null)。 Sending any request without the array works fine. 发送没有数组的任何请求都可以正常工作。

On that note, would appreciate if anyone could explain what the array looks like on the URL (if I wanted to send a request through the browser for example). 关于这一点,如果有人能解释该数组在URL上的外观(例如,如果我想通过浏览器发送请求),将不胜感激。

AJAX code: AJAX代码:

    function btnClick() {
        var arr = new Array();
        arr[0] = "Hey";
        arr[1] = "Stackoverflow";
        arr[2] = "What's your name?";

        var jsonParam = { Name: "test", Pass: "123", Stuff: arr }
        $.ajax({
            url: "Test.ashx",
            type: "get",
            data: JSON.stringify(jsonParam),
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            async:false,
            success: function (response) { 
                alert(response.Name);
            }
        });
    }

Handler code: 处理程序代码:

public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "application/json";
    JavaScriptSerializer jss = new JavaScriptSerializer();



    string res = jss.Serialize(new UserInfo { Name = context.Request.QueryString["Name"], Pass = "pass" + context.Request.QueryString["Pass"], Stuff = new string[] { "1", "2" } });
    context.Response.Write(res);
}

You cannot get the json from querystring. 您无法从查询字符串获取json。

You can use this; 您可以使用它; You should install NewtonJson for JSonConvert from nuget. 您应该安装NewtonJsonJSonConvert从的NuGet。 If you don't want that, you can use JavaScriptSerializer instead of that. 如果您不想这样做,可以使用JavaScriptSerializer代替。

    protected object FromJsonToObject(Type t)
    {
        Context.Request.InputStream.Position = 0;
        string json;
        using (var reader = new StreamReader(Context.Request.InputStream))
        {
            json = reader.ReadToEnd();
        }

        return JsonConvert.DeserializeObject(json, t);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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