【问题标题】:How to escape brackets in an ajax request?如何在ajax请求中转义括号?
【发布时间】:2017-03-14 12:26:03
【问题描述】:

我想使用 jQuery.ajax() 通过 AJAX 从输入表单中发送一个只有一个参数的 GET 请求。

为了简化事情,而不是

data: $("#the_form").serialize()

我试图显式传递输入的值:

function lookupSearch(val){
  $.ajax({
    type: "get",
    url: "/search",
    data: {
      tx_search_pi1['sword']: val
    },
    success: function(data)
    {
      $("#results").html(data);
      console.log("Success");
    }
  });
}

现在因为括号和引号而中断了

tx_search_pi1[sword]: val

(get请求的接收方要求)

如何正确转义括号(也可以在 = 内正确转义单引号?

我尝试过很多组合,例如。与

  • tx_search_pi1%5Bsword%5D
  • encodeURIComponent("tx_kesearch_pi1[sword]")
  • 等等……

【问题讨论】:

    标签: javascript jquery ajax unicode uri


    【解决方案1】:

    你可以试试这个,

    data: $("#the_form").serialize()+'&sword='val,
    

    完整代码,

    function lookupSearch(val){
      $.ajax({
        type: "get",
        url: "/search",
        data: $("#the_form").serialize()+'&sword='val,
        success: function(data)
        {
          $("#results").html(data);
          console.log("Success");
        }
      });
    }
    

    如果你想传递sword 值然后使用,

    data: {'sword':val}, // get using sword key
    

    根据@Urs Comment,代码应该是,

    // let it is initialised before,
    // and it is an object like {}, tx_search_pi1 = {key:"1",...};
    function lookupSearch(val){
      tx_search_pi1['sword'] = val;
      $.ajax({
        type: "get",
        url: "/search",
        data: tx_search_pi1,
        success: function(data)
        {
          $("#results").html(data);
          console.log("Success");
        }
      });
    }
    

    【讨论】:

    • 如果我不想序列化表单,只需告诉 .ajax:“please pass tx_search_pi1['sword']=val”?
    【解决方案2】:

    尝试将 tx_search_pi1['sword'] 这个放在一个变量中并传递它。

    喜欢

    var temp = tx_search_pi1['sword'];

    并通过温度

    【讨论】:

    • 谢谢,var temp = "tx_search_pi1['sword']"; 不会中断!跨浏览器兼容性是否安全,不需要额外的编码?
    猜你喜欢
    • 2011-04-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多