gpt4 book ai didi

javascript - Laravel:更改文本框编辑上的元素

转载 作者:行者123 更新时间:2023-12-03 04:39:18 25 4
gpt4 key购买 nike

第一个 Laravel 项目。我想制作一个表单,如果我在文本 block 中写入一些内容(例如条形码),代码就会在数据库中搜索并打印出一个值(例如价格)

到目前为止我的代码是:

View :

{{ Form::open(array('url' => '/product/$barcode'))}}
<script>
function showProduct(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","script/getproduct.php?q="+str,true);
xmlhttp.send();
}
}
</script>

//If I don't set the @vars first I get "unknown variable" error
<?php $name=0; $price=0; ?>
<table>
<tr>
<td>{{Form::text('barcode', null, ['onchange'=>'showProduct(this.value)'])}}</td>
<td><div id="txtHint">Name: {{ $name }}</div></td>
<td><div id="txtHint">Price: {{ $price }}</div></td>
</tr>
</table>
{{Form::close()}}

showproduct.php:

<?php
$q = intval($_GET['q']);

$sql = DB::select('select * from inventory where barcode = ? LIMIT 1', [$q]);

$price = $sql[0]->price;
$name = $sql[0]->name;
?>

但是当我将条形码放入文本字​​段时,字段中的值仍然是 0。我做错了什么?

最佳答案

第一个问题,您在 DOM 文档中使用了多 ID,这是完全错误的。

<td><div id="txtHint">Name: {{ $name }}</div></td>
<td><div id="txtHint">Price: {{ $price }}</div></td>

必须如下:

<td><div id="nameHint">Name: {{ $name }}</div></td>
<td><div id="priceHint">Price: {{ $price }}</div></td>

然后,在您的 php 端,您将需要 echo 一些数据,并通过将多个数据编码为 json 来发送多个数据,然后从客户端解码该 json 并将其解析为使用 JavaScript 的 DOM 元素。

所以,在您的 php 代码中,将其修改为如下:

$price = $sql[0]->price;
$name = $sql[0]->name;
echo json_encode(array("price" => $price, "name" => $name));

然后从您的客户端解码该 json,如下所示:

if (this.readyState == 4 && this.status == 200) {
var jsonObject = JSON.parse(this.responseText);
document.getElementById("priceHint").innerHTML = jsonObject['price'];
document.getElementById("nameHint").innerHTML = jsonObject['name'];
}

关于javascript - Laravel:更改文本框编辑上的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43149328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com