如何在ajax请求中转义括号?

时间:2017-03-14 12:26:04

标签: javascript jquery ajax unicode uri

我想使用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

(获取请求的收件人需要)

如何从括号中删除(也可能是单引号内=正确?

我已经尝试过许多组合,例如。与

  • tx_search_pi1%5Bsword%5D
  • encodeURIComponent方法(" tx_kesearch_pi1 [剑]&#34)
  • 等...

2 个答案:

答案 0 :(得分:1)

尝试将tx_search_pi1 ['sword']放入变量并传递给它。

var temp = tx_search_pi1 ['sword'];

并通过临时

答案 1 :(得分: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评论,代码应该是,

// 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");
    }
  });
}