我有一个使用jQuery和AJAX填充输入字段的表单。当我从动态填充的下拉列表中选择选项时,我无法在img
中更改src
网址。
JavaScript的:
$(document).ready(function(){
$("#id").change(function(){
$.ajax({
url : 'get_driver_data2.php',
type : 'POST',
dataType: 'json',
data : $('#ContactTrucks').serialize(),
success: function( data ) {
for(var id in data) {
$(id).val( data[id] );
}
}
});
});
});
PHP:
$id_selected = $_POST['id']; // Selected Id
$query = "SELECT * from admin_dispatch_records where id = '$id_selected' AND driver LIKE '%$username%'";
$result = mysqli_query($dbcon, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$eta = $row['eta'];
$time = $row['dispatch_time'];
$date = $row['dispatch_date'];
$name = $row['name'];
$phone = $row['phone'];
$vehicleyear = $row['vehicleyear'];
$color = $row['color'];
$make = $row['make'];
$model = $row['model'];
$vin = $row['vin'];
$plate = $row['plate'];
$mileage = $row['mileage'];
$pickup = $row['pickup'];
$dropoff = $row['dropoff'];
$price = $row['price'];
$invoice = $row['invoice'];
$cash = $row['cash'];
$credit = $row['credit'];
$check = $row['check'];
$po = $row['po'];
$billed = $row['billed'];
$need_to_bill = $row['need_to_bill'];
$getphoto = $row['image_path'];
}
$arr = array( 'input#eta' => $eta, 'input#dispatch_time' => $time, 'input#dispatch_date' => $date, 'input#name' => $name, 'input#phone' => $phone, 'input#vehicleyear' => $vehicleyear, 'input#color' => $color, 'input#make' => $make, 'input#model' => $model, 'input#vin' => $vin, 'input#plate' => $plate, 'input#mileage' => $mileage, 'textarea#pickup' => $pickup, 'textarea#dropoff' => $dropoff, 'input#price' => $price, 'input#invoice' => $invoice, 'input#cash' => $cash, 'input#credit' => $credit, 'input#check' => $check, 'input#po' => $po, 'input#billed' => $billed, 'input#need_to_bill' => $need_to_bill, 'image#image_path' => $getphoto);
echo json_encode($arr);
HTML的一点点:
<td>
<img id="image_path" src="????" />
</td>
</tr>
</table>
<p><strong>
<input type="submit" value="Complete Dispatch">
</strong></p>
当我更改选择框时,如何使用AJAX调用中的数据库值填充src
?填充所有其他数据并正确返回字符串。我通过放置一个输入框并包含input#image_path => $getphoto
来测试它。 img
代码的语法是否与input
或textarea
不同?我试过将PHP内联并将src
分配给$getphoto
但没有运气。我希望用AJAX传递的数据创建一个隐藏的输入字段,然后获取该数据并使其成为var,但也无法解决这个问题。
答案 0 :(得分:0)
你的意思是
if (id=="image_path") $(id).attr("src", data[id] );
else $(id).val( data[id] );
答案 1 :(得分:0)
您可以使用attr()
更改src
,如下所示:
$(id).attr("src", data[id]); // chnage the source of the img tag
在这种情况下,您可以在for
循环中使用条件语句,如下所示:
if(id=="image_path"){
$(id).attr("src", data[id]);
}else{
$(id).val(data[id]);
}
答案 2 :(得分:0)
您的JavaScript未设置src
的{{1}}属性。
在<img>
循环之后,您可以像这样从数组中提取数据:
for
或者,如果您想使用隐藏的$("#image_path").attr("src", data['image#image_path']);
方法,那将看起来像:
HTML:
<input>
PHP:
<td>
<input type="hidden" id="image_path" value="default.png" />
<img id="photo" src="default.png" />
</td>
JavaScript的:
$arr = array('input#eta' => $eta,
...
'input#image_path' => $getphoto);