簡體   English   中英

JS輸入文本以url + base64編碼

[英]JS input text to url + base64 encode

我是JS的新手,所以我將嘗試解釋這個問題。 我正在尋找一種執行以下任務的JS:輸入文本形式以在base64解碼的字符串中包含某些“文本”,然后對該字符串進行編碼。 將該編碼結果添加到網址中,並在提交時打開該網址。

base64解碼字符串類似於:

{
   "componentDef":"forceSearch:search",
   "attributes":{
      "term":"SEARCH STRING 2",
      "scopeMap":{
         "type":"TOP_RESULTS"
      },
      "context":{
         "disableSpellCorrection":false,
         "SEARCH_ACTIVITY":{
            "term":"SEARCH STRING 2"
         }
      }
   }
}

輸入的文本表單應將兩個SEARCH STRING 2替換為提交的文本,例如:

{
   "componentDef":"forceSearch:search",
   "attributes":{
      "term":"MYSUBMITEXT",
      "scopeMap":{
         "type":"TOP_RESULTS"
      },
      "context":{
         "disableSpellCorrection":false,
         "SEARCH_ACTIVITY":{
            "term":"MYSUBMITEXT"
         }
      }
   }
}

之后,結果應為base64編碼:

btoa({
   "componentDef":"forceSearch:search",
   "attributes":{
      "term":"MYSUBMITEXT",
      "scopeMap":{
         "type":"TOP_RESULTS"
      },
      "context":{
         "disableSpellCorrection":false,
         "SEARCH_ACTIVITY":{
            "term":"MYSUBMITEXT"
         }
      }

並在編碼后將結果添加到url

onClick="javascript: window.open('http://www.mywebsite.com/print/' + encoded result)"

我目前的主要問題是替換2個搜索字符串。 即時通訊無法替換,因為它的編碼?

更新:

我目前有此代碼,但編碼始終相同,因此我不希望用戶輸入文本值:

<html>

<script type="text/javascript">

function goToPage() {
var searchQuery = document.getElementById('text').value;
var stringToEncode = '{"componentDef":"forceSearch:search","attributes":{"term":"'+ searchQuery + '","scopeMap":{"type":"TOP_RESULTS"},"context":{"disableSpellCorrection":false,"SEARCH_ACTIVITY":{"term":"'+ searchQuery + '"}}}}';
var encodedString = btoa(stringToEncode);
document.write("http://www.mywebsite.com/print/" + encodedString);
}
</script>
<input type="text" id="text" />
<input type="submit" value="submit" onclick="goToPage();" />
</html>
  1. 使用JSON.parse將字符串解析為JavaScript對象
var myString = '{"componentDef":"forceSearch:search","attributes":{"term":"SEARCH STRING 2","scopeMap":{"type":"TOP_RESULTS"},"context":{"disableSpellCorrection":false,"SEARCH_ACTIVITY":{"term":"SEARCH STRING 2"}}}}';

var myObject = JSON.parse(myString);
  1. 訪問對象中的屬性並將其替換為所需的值
myObject.attributes.term = 'New value';
myObject.attributes.context.term = 'New value';
  1. 將對象轉換回字符串並使用base64對其進行編碼
var newString = JSON.stringify(myObject);
var encodedString = btoa(newString);

點擊處理程序

<a href="#" onclick="javascript:window.open('http://www.mywebsite.com/print/' + encodedString)">Click here</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM