我是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"
}
}
,编码后应将结果添加到网址
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>
答案 0 :(得分: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);
myObject.attributes.term = 'New value';
myObject.attributes.context.term = 'New value';
var newString = JSON.stringify(myObject);
var encodedString = btoa(newString);
点击处理程序
<a href="#" onclick="javascript:window.open('http://www.mywebsite.com/print/' + encodedString)">Click here</a>