簡體   English   中英

如何在PHP中添加從AJAX請求中選擇的表單選項

[英]How to add option to select form as received from AJAX request in PHP

添加選項以選擇AJAX接收的框數據的方法是什么

HTML:

<select id="options"></select>

jQuery的:

$.ajax({
  type: "POST",
  url: "ajax/addCustDetail.php",
  data: {customerId},
  cache: false,
  success: function(html)
  {
    $("#options").html(html);
  } 
});

有兩種方法可以做到這一點:

  1. 通過從addCustDetail.php返回字符串,如:

     $response = '<option value="1">One</option><option value="2">Two</option>'; 

並且這個$response被重新調整,在這種情況下你可以簡單地在jquery中使用它:

    $("#options").html(html);
  1. 如果從addCustDetail.php返回一個json數組,那么你在jquery中解析它並迭代它並創建選項然后在select中添加它們。

PHP邊碼:

$cid=$_POST['cid'];
$query="SELECT * from customer_shipping_address WHERE STransNo=$cid";        
$result1 = mysqli_query($con, $query);
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
    echo "<option value=".$row['TransSlNo'].">".$row['ShipName']."</option>" ;   
}

您可以將子項附加到select元素,如下所示:

首先,在select元素中添加一個id:

<select id="myselect"></select>

然后像這樣追加孩子:

var selectElement = document.getElementById("myselect");
var newOption = document.createElement("option");
newOption.innerHTML = "New option!";
selectElement.appendChild(newOption);

假設您現在從ajax請求接收數組,您可以創建一個循環並使用上面的代碼來添加選項。 例:

for(let i = 0; i < 7; i++) {
   var newOption = document.createElement("option");
   newOption.innerHTML = response[i].name;
   newOption.setAttribute("value", response[i].value);
   selectElement.appendChild(newOption);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM