如何从 php 获取 json 数据到 javascript

问题描述 投票:0回答:1

我已经这样做了,只是一个问题。哪个值,javascript在数据库中给出php .php搜索。如果找到结果,则发送结果,如果未找到,则发送未找到的数据。我已经尝试过,如...请参阅下面的代码。

//javascript code
<script>
 function arii(val) {
                     fetch(`<?php echo $_SESSION['base_url'] ?>nazad_return_from_buyer/api.php?id=${val}`)
                    .then((response) => response.json())
                    .then((data) => {
                     document.querySelector('#invoice').value = parseInt(data);})
                    }
</script>
//html code
<select name="order_id" id="order_id"  onchange="arii(this.value)">
      <option value="">Select one</option>
      <option value="7">Nazad</option>
      <option value="8">Tanvir</option>
      <option value="9">Bosundhara</option>
</select>
//php code
<?php
$id = $_GET['id'];
$con=new mysqli("localhost","root","","production_automation");
$result=$con->query("select shipping.invoice_id from shipping where order_id=$id")->fetch_assoc();
$data=$result['invoice_id'] ;

header('Content-Type: application/json;');
echo json_encode($data);
?>
//here will show result
<div>
 <input id="invoice">
</div>

注:[ 如果在输入的数据库中找不到任何结果,将显示“未找到数据” ]

javascript php json ajax
1个回答
0
投票
//javascript code
<script>
 function arii(val) {
                     fetch(`<?php echo $_SESSION['base_url'] ?>nazad_return_from_buyer/api.php?id=${val}`)
                    .then((response) => response.json())
                    .then((data) => {
                     document.querySelector('#invoice').value = parseInt(data);})
                    }enter code here
</script>
//html code
<select name="order_id" id="order_id"  onchange="arii(this.value)">
      <option value="">Select one</option>
      <option value="7">Nazad</option>
      <option value="8">Tanvir</option>
      <option value="9">Bosundhara</option>
</select>
//php code
<?php
$id = $_GET['id'];
$con=new mysqli("localhost","root","","production_automation");
$result=$con->query("select shipping.invoice_id from shipping where order_id=$id")->fetch_assoc();
if (isset($result['invoice_id']))
{
$data=$result['invoice_id'];`enter code here`
}else {
$data={"invoice_id:''"};
}

header('Content-Type: application/json;');
echo json_encode($data);
?>
//here wienter code herell show result
<div>
 <input id="invoice">
</div>
© www.soinside.com 2019 - 2024. All rights reserved.