用于将数据发布到 ASP.Net 页面的 jQuery AJAX 调用(不是 Get 而是 POST)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14095041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:16:05  来源:igfitidea点击:

jQuery AJAX Call for posting data to ASP.Net page ( not Get but POST)

asp.netjquerypost

提问by Sunil

I have the following jQuery AJAX call to an ASP.Net page.

我有以下对 ASP.Net 页面的 jQuery AJAX 调用。

             $.ajax({
                async: true,
                type: "POST",
                url: "DocSummaryDataAsync.aspx", //"DocSummary.aspx/GetSummaryByProgramCount",
                contentType: "application/json; charset=utf-8",
                data: kendo.stringify({ vendorId: supplierId, businessUnit: busUnit, productSegmentId: prodSegmentId, programId: progId, productManagerId: prodManagerId, companyIds: compIds, expired: exp.toString(), requestType: 'TotalCount' }),
                success: function (msg) {
                    // alert('in success of getcount');

                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    // alert('in failure of getcount');


                }
            });

When I try to retrieve from Request object, the posted data, it does not show up. My aspx page code is as below. I am sending each of posted data in Json format to the page, yet it doesn't show up in code-behind of page. Is there some extra setting in jQuery ajax call that I am missing?

当我尝试从 Request 对象中检索已发布的数据时,它没有显示出来。我的 aspx 页面代码如下。我以 Json 格式将每个发布的数据发送到页面,但它没有显示在页面的代码隐藏中。jQuery ajax 调用中是否有一些我缺少的额外设置?

   protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "application/json";

        string requestType = Request.Params["requestType"];


        //populate variables from posted data
        string vendorId = Request.Params["vendorId"];
        string businessUnit = Request.Params["businessUnit"];
        string productSegmentId = Request.Params["productSegmentId"];
        string commitmentProgramId = Request.Params["programId"];
        string productManagerId = Request.Params["productManagerId"];
        string companyIds = Request.Params["companyIds"];
        string expired = Request.Params["expired"];
     }

UPDATE 1:Stephen's answer is the best approach to this, especially the approach that does ProcessRequest. However, I did find a small trick that will allow data to be posted to ASP.Net in the usual traditional manner i.e. like Request["vendorId"] etc. To enable such posting of data from any jQuery ajax request, you simply need to make sure that the following 2 points are applied to your jQuery ajax call:

更新 1:斯蒂芬的回答是最好的方法,尤其是执行 ProcessRequest 的方法。但是,我确实找到了一个小技巧,它允许以通常的传统方式将数据发布到 ASP.Net,例如 Request["vendorId"] 等。要从任何 jQuery ajax 请求中启用此类数据发布,您只需要确保将以下 2 点应用于您的 jQuery ajax 调用:

  1. The content-type should be left out of your jQuery ajax callOr if you want to include it then it should not be set to"application/json; charset=utf-8" but to "application/x-www-form-urlencoded; charset=UTF-8". Content-type, as per my understanding is telling the ASP.Net page the type of data that is being sent, and not the type of data that is expected of the page.
  2. The data part of jQuery ajax should not have the data names enclosed in quotes. So data: {"venorId":"AD231","businessUnit":"123"} should be replaced by data: {vendorId:"AD231",businessUnit:"123"}. In this example the data names are vendorId and businessUnit, which can be accessed in your ASP.Net code-behind using usual ASP.Net syntax like Request["vendorId"] and Request["businessUnit"].
  1. 内容类型应该被排除在你的 jQuery ajax 调用之外或者如果你想包含它,那么它不应该被设置为“application/json; charset=utf-8”而是“application/x-www-form-urlencoded ; 字符集 = UTF-8"。内容类型,根据我的理解是告诉 ASP.Net 页面正在发送的数据类型,而不是页面预期的数据类型。
  2. jQuery ajax 的数据部分不应将数据名称括在引号中。所以数据:{"venorId":"AD231","businessUnit":"123"} 应该替换为数据:{vendorId:"AD231",businessUnit:"123"}。在此示例中,数据名称是 vendorId 和 businessUnit,可以在 ASP.Net 代码隐藏中使用常见的 ASP.Net 语法(如 Request["vendorId"] 和 Request["businessUnit"])访问它们。

回答by Stephen Oberauer

Option 1. Keep your server side code the same

选项 1.保持服务器端代码相同

First remove the kendo.stringify. Then either remove the contentType or change it to...

首先删除kendo.stringify。然后删除 contentType 或将其更改为...

"application/x-www-form-urlencoded; charset=utf-8" 

...or change your $.ajax call to this:

...或将您的 $.ajax 调用更改为:

$.post('DocSummaryDataAsync.aspx', { vendorId: supplierId, businessUnit: busUnit, productSegmentId: prodSegmentId, programId: progId, productManagerId: prodManagerId, companyIds: compIds, expired: exp.toString(), requestType: 'TotalCount' }, function (data) { });

Option 2. Change the POST to GET

选项 2.将 POST 更改为 GET

Like this

像这样

$.ajax({
async: true,
type: "GET",
etc.

This will pass your data via the QueryString. If you remove the kendo.stringifycall you would access all the values like this:

这将通过 QueryString 传递您的数据。如果您删除kendo.stringify调用,您将访问如下所有值:

string vendorId = Request.QueryString[0];
string businessUnit = Request.QueryString[1];
etc.

Option 3. Use your original $.ajax call

选项 3.使用您原来的 $.ajax 调用

If you use your original $.ajax, then the following applies:

如果您使用原始的 $.ajax,则以下内容适用:

Request.Params gets a "combined collection of QueryString, Form, Cookies, and ServerVariables items." - this link

Request.Params 获得“QueryString、Form、Cookie 和 ServerVariables 项的组合集合”。-这个链接

You are not working with any of those. Instead, you need to access Request.InputStream.

您没有与其中任何一个合作。相反,您需要访问 Request.InputStream。

Here's how you can do that:

您可以这样做:

Create a class on the server side which maps to the requested JSON object, e.g.

在服务器端创建一个映射到请求的 JSON 对象的类,例如

public class MyClass
{
    // The type (int or string) should probably correspond to the JSON
    public int vendorId { get; set; }
    public string businessUnit { get; set; }
    public string productSegmentId { get; set; }
    public string programId { get; set; }
    public string productManagerId { get; set; }
    public string companyIds { get; set; }
    public string expired { get; set; }
    public string requestType { get; set; }
}

Convert Request.InputStream into that type, and then you can use it.

将 Request.InputStream 转换成那个类型,然后就可以使用了。

public void ProcessRequest()
{
    System.IO.Stream body = Request.InputStream;
    System.Text.Encoding encoding = Request.ContentEncoding;
    System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
    string json = reader.ReadToEnd();
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    MyClass myclass = (MyClass)serializer.Deserialize(json, typeof(MyClass));
    int vendorId = myclass.vendorId;
    string requestType = myclass.requestType;
    // etc...
}

protected void Page_Load(object sender, EventArgs e)
{
    ProcessRequest();
}