【发布时间】:2013-03-12 16:13:23
【问题描述】:
我应该如何在 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 个赞(我一开始没有找到它是我的坏事):
Using jquery to make a POST, how to properly supply 'data' parameter?
这完美地回答了我的问题,我发现这样做更容易阅读并且我不需要在 URL 或 DATA 值中手动使用encodeURIComponent()(这是我在 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) {
}
});
【问题讨论】:
-
$.get 只是 $.ajax 的快捷方式
-
除了,您的 Edit 09/04/2013 是一个发布请求 :-) 但它显然与 GET 相同。
标签: javascript jquery ajax get