asp.net jquery ajax json: Simple example of exchan

2020-03-25 02:20发布

问题:

(Question resolved with the help of the two reply posts--see below)

I would appreciate help getting a simple example of exchanging data JSON data between a browser (using JavaScript/JQuery) and ASP.NET (using Visual Studio 2010).

When I click a button the following is executed:

 <script type="text/javascript">
    bClick = function () {
        var myData = { "par": "smile" };
        alert("hi "+myData.par);
        $.ajax({
            url: "ericHandler.ashx",
            data: myData,
            dataType: 'json',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            success: function (data) { alert("DIDit = " + data.eric); },
            error: function (data, status, jqXHR) { alert("FAILED:" + status); }
        });
    }
</script>

In Visual Studio, I have the following code associated with an ashx file. When I run it and click the button, everything works as expected except I don't see myData passed to the C# code--I am looking at context.Request.QueryString in the debugger and it shows "{}".

I have seen examples using

string stringParam = (string)Request.Form("stringParam");

but Visual Studio "Request" does not seem to be defined. All I want to do is see data move both ways, and I appear to be half way there. Any help would be appreciated.

--C# code--

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CSASPNETSerializeJsonString
{
/// <summary>
/// Summary description for ericHandler
/// </summary>
public class ericHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string rq = context.Request.QueryString["par"];

        context.Response.ContentType = "application/json";
        context.Response.Write("{\"eric\":\"12345\"}");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

}

* RESOLVED First, if you want to send some form parameters from JavaScript to ASP.NET one should use the ajax call in the second post below and do NOT use stringify on the data. In other words, if don't specify the data being sent is json the lack of any specification defaults to 'application/x-www-form-urlencoded'). This will causes the object's fields to be appended in a "url" format (field=X&field2=Y&field3=Z..) and thus shows up in ASP.NET using Request.Form["field"].

Second, if you really do want to send JSON data, then specify this type is what is being sent (like I have done above) and use the InputStream on the receiving side. Further parsing of the received string is then required to get at the field values.

In my example, I am sending back JSON data having "manually" encoded it into a string. I believe there is a JSON serialization routine so that C# objects can be sent over.

回答1:

Other resource suggest removing the contentType: 'application/json; charset=utf-8', from the AJAX call:

  $.ajax({ 
            url: "ericHandler.ashx", 
            data: myData, 
            dataType: 'json', 
            type: 'POST', 
            success: function (data) { alert("DIDit = " + data.eric); }, 
            error: function (data, status, jqXHR) { alert("FAILED:" + status); } 
        }); 

Read the values on the server side:

string myPar = context.Request.Form["par"]; 

You can also try:

string json = new StreamReader(context.Request.InputStream).ReadToEnd(); 

which was mentioned here: https://stackoverflow.com/a/8714375/139917



回答2:

I got this working right away. This is its most basic form:

HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: 'Handler.ashx',
                type: 'POST',
                success: function (data) {
                    alert(data);

                },
                error: function (data) {
                    alert("Error");
                }
            });
        });
    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">

    </form>
</body>
</html>

Code Behind:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("Hello World");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}