javascript - 如何在点击发布请求时以双引号传递变量
问题描述
我想在点击发布 Api 请求时将personName作为双引号中的变量传递。这是供您参考的代码片段。
var ItemJSON = '{"filters":{"keyword":"' + **personName** + '","award_type_codes":["09","11"]},"fields":["Award ID","Mod","Recipient Name","Action Date","Transaction Amount","Awarding Agency","Awarding Sub Agency","Award Type"],"page":1,"limit":50,"sort":"Transaction Amount","order":"desc"}';
var scriptHash = "var xmlhttp = new XMLHttpRequest();" +
"xmlhttp.open('POST', 'https://api.usaspending.gov/api/v2/search/spending_by_transaction/');" +
"xmlhttp.setRequestHeader('Content-Type', 'application/json');" +
"xmlhttp.onreadystatechange = function()" +
"{" +
"document.body.innerHTML = '';" +
"var el = document.createElement('entirely-unique-other-search');" +
"el.innerText = xmlhttp.responseText;" +
"document.querySelector('body').append(el);" +
"};" +
"xmlhttp.send(\'" + ItemJSON + "\');";
driver.executeScript(scriptHash);
提前致谢。
解决方案
您可以使用JSON.stringify
将对象转换为字符串。
var ItemJSON = {
filters: { keyword: personName, award_type_codes: ['09', '11'] },
fields: [
'Award ID',
'Mod',
'Recipient Name',
'Action Date',
'Transaction Amount',
'Awarding Agency',
'Awarding Sub Agency',
'Award Type'
],
page: 1,
limit: 50,
sort: 'Transaction Amount',
order: 'desc'
};
var scriptHash =
'var xmlhttp = new XMLHttpRequest();' +
"xmlhttp.open('POST', 'https://api.usaspending.gov/api/v2/search/spending_by_transaction/');" +
"xmlhttp.setRequestHeader('Content-Type', 'application/json');" +
'xmlhttp.onreadystatechange = function()' +
'{' +
"document.body.innerHTML = '';" +
"var el = document.createElement('entirely-unique-other-search');" +
'el.innerText = xmlhttp.responseText;' +
"document.querySelector('body').append(el);" +
'};' +
"xmlhttp.send('" +
JSON.stringify(ItemJSON) + // <-- convert ItemsJSON to string
"');";
driver.executeScript(scriptHash);
推荐阅读
- node.js - 我怎样才能让 Jasmine 在我的期望调用之前等待,以便等待返回数据后执行的代码运行?
- scala - 可选功能在这里是什么意思?
- python - Pandas 数据框 - 获取列索引以获取连续最小值
- cron - 如何调用重启服务
- php - ImageMagick 裁剪图像的非正方形区域
- git - 为什么 git 会与我自己在同一分支的提交产生冲突?
- powershell - 无法使用 powershell 执行 Jenkins 作业
- database - 如何使用 Heroku 运行 pg_dumpall?
- python - ffmpeg 创建的 mp4 无法与 IPython.display.Video 一起播放
- jasper-reports - 如何在子数据集中将一个字段引用到另一个字段?