【问题标题】:Autocomplete using json and multiple variables使用 json 和多个变量自动完成
【发布时间】:2021-06-22 17:54:24
【问题描述】:

想知道是否有人可以为我指明正确的方向。

这是项目的主页(index.php)。下面的脚本从正确显示的 fetch.php 接收值。我只需要自动完成 2 个输入框 client_idtitle。我知道问题出在脚本上,但无法弄清楚。

   <input type="text" id="client_id" name="client_id" placeholder="ID"  />
   <input type="text" id="status" name="status" placeholder="Status" autocomplete="off"  />
   <input type="text" id="title" name="title" placeholder="Client"   autocomplete="off" />              



function setText(obj){
var val = obj.value;
console.log(val);

function concat(){
            
            var x = <?php echo $client_id; ?>
            var y = <?php echo $first_name; ?>
            document.getElementById("client_id").value = x;
            document.getElementById("title").value = y;
            }
            concat();

}

如果有以下脚本,标题会自动填写。

function setText(obj){
var val = obj.value;
console.log(val);
document.getElementById('title').value = val;
}

【问题讨论】:

  • Javascript 字符串需要被引用。试试这个:var x = "&lt;?php echo $client_id; ?&gt;";var y = "&lt;?php echo $first_name; ?&gt;";(我不知道你的 client_id 是 int 还是 string,因为它被放入文本框中,引用它是安全的。
  • @wetmarble 只是添加引号是不安全的,即名字 = ";alert('xss');",应该使用 json_encode 而不是 var y = &lt;?= json_encode($first_name); ?&gt;;,只是说

标签: php json ajax


【解决方案1】:

您以一种没有意义的方式将 php 与 javascript 混合在一起,因为您说这些值来自 fetch

如果真的是 PHP,那么(显然)你可以直接设置输入

   <input type="text" id="client_id" name="client_id" placeholder="ID"  value="<?php echo $client_id; ?>" />
   <input type="text" id="status" name="status" placeholder="Status" autocomplete="off"  />
   <input type="text" id="title" name="title" placeholder="Client"   autocomplete="off" value=" <?php echo $first_name; ?>" />              

如果它是通过 fetch 进来的,你可以这样做:

let ref = 12; // the reference to get the data
fetch(`http://example.com/getClientData.php?ref=${ref}`)
  .then(response => response.json())
  .then(data => {
    document.getElementById("client_id").value = data.client_id;
    document.getElementById("title").value =  data.client_title;
    console.log(data)
  });

【讨论】:

    猜你喜欢
    • 2022-10-23
    • 2013-02-02
    • 2013-01-06
    • 2013-03-08
    • 2017-08-14
    • 2012-11-06
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多