JavaScript如何替换URL关键字段查询不同数据,有类似Python f-string的用法吗?
解决方案
JavaScript中和Python f-string功能完全对应的是模板字符串(Template Literals),使用反引号 ` 包裹字符串内容,变量/表达式使用${}包裹插入即可,用法和f-string几乎一致。
基础用法示例
你要拼接请求URL可以直接这么写:
// 假设获取到用户输入的关键词 const deviceName = '用户输入的关键词' const requestUrl = `https://api.fda.gov/device/510k.json?search=device_name:${deviceName}&limit=1000`
结合你的DataTable场景改造
你需要先给页面加一个关键词输入框和搜索触发按钮,然后在触发搜索时动态修改DataTable的请求地址并重载数据,完整参考代码如下:
<!-- 页面先加输入控件 --> <input type="text" id="deviceKeyword" placeholder="请输入设备关键词"> <button id="searchBtn">搜索</button> <table id="example"></table>
$(document).ready(function () { // 初始化DataTable var table = $('#example').DataTable({ ajax: { // 默认先搜索glucose url: 'https://api.fda.gov/device/510k.json?search=device_name:glucose&limit=1000', dataSrc: 'results', cache: true, }, // 补充你自己的列配置、分页配置等代码即可 columns: [ // 你的自定义列定义 ] }) // 绑定搜索按钮点击事件 $('#searchBtn').on('click', function() { const keyword = $('#deviceKeyword').val().trim() if (!keyword) return // 用模板字符串拼接新的请求地址 const newUrl = `https://api.fda.gov/device/510k.json?search=device_name:${keyword}&limit=1000` // 修改DataTable的ajax地址并重载数据 table.ajax.url(newUrl).load() }) })
内容的提问来源于stack exchange,提问作者TwoTimer
相关产品推荐
相关产品推荐

