首页 > 解决方案 > 如何在点击发布请求时以双引号传递变量

问题描述

我想在点击发布 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);

提前致谢。

标签: javascriptjsonselenium-webdriver

解决方案


您可以使用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);

推荐阅读