elliott.david 2013-03-22 17:33 采纳率: 25%
浏览 3305
已采纳

如何通过 jQuery 传递 GET 请求中的参数?

如何在jQueryAjax请求中传递查询字符串值?我目前这样做,但我相信有一个更干净的方式,不需要我手动编码。

$.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:

在我的问题解决后(因为“过于本地化”),我发现了一个类似的问题:

如何使用jQuery来发布文章,如何正确地提供“数据”参数?

这完美地回答了我的问题,我发现这样做更容易阅读,而且我不需要在URL或数据值中手动使用 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) {

    }
});
  • 写回答

8条回答 默认 最新

  • Didn"t forge 2013-03-22 17:35
    关注

    Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method

    Try this

    $.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
      }
    });
    

    And you can get the data by (if you are using PHP)

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

    In aspx, I believe it is (might be wrong)

     Request.QueryString["ajaxid"].ToString(); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?