2017-03-14 20 views
0

我想通過AJAX使用jQuery.ajax()通過AJAX從輸入表單發送一個只有一個參數的GET請求。如何在ajax請求中轉義括號?

爲了簡化而不是

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 [刀劍]」)
  • 等...

回答

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 

As p呃@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"); 
    } 
    }); 
} 
+0

如果我不想序列化表單,請告訴.ajax:「請通過tx_search_pi1 ['sword'] = val」? – Urs

+0

查看我的更新回答。 –

1

嘗試把tx_search_pi1 [ '劍']這一個變量,交上來。

喜歡

變種臨時= tx_search_pi1 [ '劍'];

,並通過臨時

+0

謝謝,'var temp =「tx_search_pi1 ['sword']」;'不會中斷!這是否安全,跨瀏覽器兼容性不需要額外的編碼? – Urs