ajax如何调用ashx中,ajax-ASP.NET-将JSON从jQuery传递到ASHX

ajax-ASP.NET-将JSON从jQuery传递到ASHX

我正在尝试将JSON从jQuery传递到.ASHX文件。 下面的jQuery示例:

$.ajax({

type: "POST",

url: "/test.ashx",

data: "{'file':'dave', 'type':'ward'}",

contentType: "application/json; charset=utf-8",

dataType: "json",

});

如何检索.ASHX文件中的JSON数据? 我有方法:

public void ProcessRequest(HttpContext context)

但我在请求中找不到JSON值。

8个解决方案

56 votes

我知道这太旧了,不过为了记录,我想加5美分

您可以使用此方法读取服务器上的JSON对象

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

Claudio Redi answered 2020-08-10T03:29:11Z

24 votes

以下解决方案为我工作:

客户端:

$.ajax({

type: "POST",

url: "handler.ashx",

data: { firstName: 'stack', lastName: 'overflow' },

// DO NOT SET CONTENT TYPE to json

// contentType: "application/json; charset=utf-8",

// DataType needs to stay, otherwise the response object

// will be treated as a single string

dataType: "json",

success: function (response) {

alert(response.d);

}

});

服务器端.ashx

using System;

using System.Web;

using Newtonsoft.Json;

public class Handler : IHttpHandler

{

public void ProcessRequest(HttpContext context)

{

context.Response.ContentType = "text/plain";

string myName = context.Request.Form["firstName"];

// simulate Microsoft XSS protection

var wrapper = new { d = myName };

context.Response.Write(JsonConvert.SerializeObject(wrapper));

}

public bool IsReusable

{

get

{

return false;

}

}

}

Andre answered 2020-08-10T03:29:39Z

4 votes

如果您将数据发送给服务器DataContractJsonSerializer,则该数据将不会自动转换为JSON数据(请参阅如何构建JSON对象以发送到AJAX WebService?)。 因此,您可以使用context.Request.QueryString["type"]和dataType: "json",而不要使用JSON.stringify或$.toJSON不转换数据。

data: "{'file':'dave', 'type':'ward'}"

(将数据手动转换为JSON),您可以尝试使用

data: {file:'dave', type:'ward'}

并使用DataContractJsonSerializer和context.Request.QueryString["type"]构造在服务器端获取数据。 如果您确实收到这种方式的问题,则可以尝试

data: {file:JSON.stringify(fileValue), type:JSON.stringify(typeValue)}

和使用在服务器端DataContractJsonSerializer。

Oleg answered 2020-08-10T03:30:13Z

2 votes

html

js

(function($) {

$(document).ready(function() {

$('#getReport').click(function(e) {

e.preventDefault();

window.location = 'pathtohandler/reporthandler.ashx?from={0}&to={1}'.f('01.01.0001', '30.30.3030');

});

});

// string format, like C#

String.prototype.format = String.prototype.f = function() {

var str = this;

for (var i = 0; i < arguments.length; i++) {

var reg = new RegExp('\\{' + i + '\\}', 'gm');

str = str.replace(reg, arguments[i]);

}

return str;

};

})(jQuery);

c#

public class ReportHandler : IHttpHandler

{

private const string ReportTemplateName = "report_template.xlsx";

private const string ReportName = "report.xlsx";

public void ProcessRequest(HttpContext context)

{

using (var slDocument = new SLDocument(string.Format("{0}/{1}", HttpContext.Current.Server.MapPath("~"), ReportTemplateName)))

{

context.Response.Clear();

context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", ReportName));

try

{

DateTime from;

if (!DateTime.TryParse(context.Request.Params["from"], out from))

throw new Exception();

DateTime to;

if (!DateTime.TryParse(context.Request.Params["to"], out to))

throw new Exception();

ReportService.FillReport(slDocument, from, to);

slDocument.SaveAs(context.Response.OutputStream);

}

catch (Exception ex)

{

throw new Exception(ex.Message);

}

finally

{

context.Response.End();

}

}

}

public bool IsReusable { get { return false; } }

}

oyaebunterkrah answered 2020-08-10T03:30:28Z

1 votes

这适用于调用Web服务。 不确定.ASHX

$.ajax({

type: "POST",

url: "/test.asmx/SomeWebMethodName",

data: {'file':'dave', 'type':'ward'},

contentType: "application/json; charset=utf-8",

dataType: "json",

success: function(msg) {

$('#Status').html(msg.d);

},

error: function(xhr, status, error) {

var err = eval("(" + xhr.responseText + ")");

alert('Error: ' + err.Message);

}

});

[WebMethod]

public string SomeWebMethodName(string file, string type)

{

// do something

return "some status message";

}

Larry Flewwelling answered 2020-08-10T03:30:48Z

0 votes

您必须在Web配置文件中定义处理程序属性,以处理用户定义的扩展请求格式。 用户定义的扩展名是“ .api”

添加动词=“ *” path =“ test.api” type =“ test”将网址:“ / test.ashx”替换为网址:“ / test.api”。

Ashish Sharma answered 2020-08-10T03:31:12Z

-1 votes

如果使用$ .ajax并使用.ashx获取querystring,则不要设置数据类型

$.ajax({

type: "POST",

url: "/test.ashx",

data: {'file':'dave', 'type':'ward'},

**//contentType: "application/json; charset=utf-8",

//dataType: "json"**

});

我得到它的工作!

user411861 answered 2020-08-10T03:31:37Z

-4 votes

尝试System.Web.Script.Serialization.JavaScriptSerializer

随着铸造到字典

Dewfy answered 2020-08-10T03:32:01Z

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值