asp.net jquery ajax json数据,asp.net jquery ajax json: Simple example of exchan

杨景山
2023-12-01

(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:

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); }

});

}

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 description for ericHandler

///

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.

 类似资料: