小编典典

如何使用 jQuery 在 GET 请求中传递参数

all

我应该如何在 jQuery Ajax 请求中传递查询字符串值?我目前按如下方式进行操作,但我确信有一种更简洁的方式不需要我手动编码。

$.ajax({
    url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
    success: function(response) {
        //Do Something
    },
    error: function(xhr) {
        //Do Something to handle error
    }
});

我看到了查询字符串参数作为数组传递的示例,但我看到的这些示例不使用$.ajax()模型,而是直接转到$.get(). 例如:

$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );

我更喜欢使用 $.ajax() 格式,因为这是我习惯的(没有特别好的理由 - 只是个人喜好)。

编辑 09/04/2013:

在我的问题被关闭(作为“过于本地化”)之后,我发现了一个相关的(相同的)问题 - 有 3 个赞成票(我一开始没有找到它是我的坏事):

使用 jquery 进行 POST,如何正确提供 ‘data’
参数?

这完美地回答了我的问题,我发现这样做更容易阅读并且我不需要encodeURIComponent()在 URL 或 DATA 值中手动使用(这是我在
bipen
的答案中发现的不清楚)。这是因为该data值是通过$.param())
自动编码的。以防万一这对其他人有用,这是我使用的示例:

$.ajax({
    url: "ajax.aspx?ajaxid=4",
    data: { 
        "VarA": VarA, 
        "VarB": VarB, 
        "VarC": VarC
    },
    cache: false,
    type: "POST",
    success: function(response) {

    },
    error: function(xhr) {

    }
});

阅读 67

收藏
2022-04-20

共1个答案

小编典典

使用 ajax 的数据选项。data您可以通过ajax
中的选项将数据对象发送到服务器,该选项type定义了您发送它的方式(POST或者GET)。默认类型是GET方法

试试这个

$.ajax({
  url: "ajax.aspx",
  type: "get", //send it through get method
  data: { 
    ajaxid: 4, 
    UserID: UserID, 
    EmailAddress: EmailAddress
  },
  success: function(response) {
    //Do Something
  },
  error: function(xhr) {
    //Do Something to handle error
  }
});

您可以通过(如果您使用 PHP)获取数据

 $_GET['ajaxid'] //gives 4
 $_GET['UserID'] //gives you the sent userid

在aspx中,我相信是(可能是错误的)

 Request.QueryString["ajaxid"].ToString();
2022-04-20