如何将数据从JQuery Ajax发送到ASP.网络页面

How to send data from JQuery Ajax to ASP.NET page?

本文关键字:ASP 网络 Ajax 数据 JQuery      更新时间:2023-09-26

我使用JQuery Ajax将数据从一个域发送到另一个域中的ASP.NET页面。我能够从ASP.NET页面获得响应,但我无法从JQuery Ajax发送数据。下面是我的代码:

        $.ajax({
            url: 'http://somewebsite/dbd/leap.aspx',
            data: '{ year: "' + $('#txtYear').val() + '"}',
            type: 'POST',
            async: true,
            cache: false,
            dataType: 'jsonp',
            crossDomain: true,
            contentType:"application/json; charset=utf-8",
            success: function (result) {
                console.log("inside sucess");
                console.log("result: " + result);
            },
            error: function (request, error) {
                // This callback function will trigger on unsuccessful action                
                alert('Error!');
            }
        });

我可以到达leap.aspx页面。注意http://somewebsite只是一个占位符。

leap.aspx有以下内容:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="leap.aspx.cs" Inherits="_Default" %>
<%=output %>

leap.aspx.cs有以下内容:注意,我使用Request.Params["year"]来获取Ajax调用传递的年份值,但没有运气。

using System;
public partial class _Default : System.Web.UI.Page 
{
public string output = "";
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Params["callback"] != null)
    {
        output = Request.Params["callback"] + "('" + GetData(Request.Params["year"]) + "')";
    } 
}
[System.Web.Services.WebMethod]
public string GetData(string year)
{  
return "From outer space! " + year;
}

}

当我运行这段代码时,在控制台中我看到

"result: From outer space!"

但是我没有看到Ajax发送的年数据。我正在使用JSONP,因为我正在进行跨域请求以绕过同源策略。我没有得到任何错误。我只是没有得到从ASP.NET页返回的年份值。

我怎么得到年份?

更改数据设置以删除引号,如下所示:

data: { year: $('#txtYear').val() },

在预定义对象中遇到同样的问题,这对我很有帮助。