[英]How to submit form with dynamic html Input texbox using jQuery Ajax
我正在使用jQuery創建動態多個HTML輸入框並填充值,填充后我想在每個文本框中更新產品價格,並使用ajax將更新后的值提交給服務器。 我面臨着以下代碼的問題,如果我在文本框中編輯產品價格並點擊更新按鈕,它調用我的ajax功能,但更新產品價格不發送到服務器。 我變得空虛了。
如果我單擊“更新”按鈕,我將獲得以下代碼的空數組:
JSON.stringify($("#updateNameForm").serializeArray())
出於某種原因,我的動態文本框更新了不會出現在ajax方法中的值。
請找到我的以下代碼 - 有人可以幫助我在這里做錯了以及如何解決問題。 完整代碼:
來自服務器端的JSON:
[{
"productName": "Product1",
"productPrice": "323"
}, {
"productName": "Product2",
"productPrice": "4333"
}]
HTML代碼:
<div class="content-wrapper">
<section class="content">
<div class="row">
<div class="col-md-9">
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">My Form</h3>
</div>
<!-- /.box-header -->
<form id="updateNameForm" class="form-horizontal" method="post">
<div class="box-body">
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox" id="editName" class="input_control" /> <strong> Edit</strong>
</label>
</div>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-default">Cancel</button>
<input id="updateName" type="button" name="updatea" value="Update" class="btn btn-info pull-right">
</div>
</form>
</div>
</div>
</div>
</section>
</div>
更新Ajax
$("#updateName").on('click', function() {
$.ajax({
url: 'myApp/updateProduct',
type: "PUT",
dataType: 'json',
data: JSON.stringify($("#updateNameForm").serializeArray()),
success: function(result) {
alert(result);
},
error: function(e) {
console.log(e.responseText);
}
});
});
loadProduct函數
function loadProduct() {
$.ajax({
url: 'myApp/getProduct',
type: "GET",
dataType: 'json',
success: function(productJson) {
$.each(JSON.parse(JSON.stringify(productJson)), function(idx, obj) {
var formgroup = $("<div/>", {
class: "form-group"
});
formgroup.append($("<label>", {
class: "col-sm-2 control-label",
text: obj.productName
}));
var colsm = $("<div/>", {
class: "col-sm-10"
});
var input = $("<input/>", {
type: "text",
class: "form-control",
id: obj.productName + "Id",
value: obj.productPrice
});
colsm.append(input);
formgroup.append(colsm);
$(".box-body").append(formgroup);
});
},
error: function(e) {
console.log(e.responseText);
}
});
}
謝謝!
您沒有為輸入字段指定name
。
var input = $("<input/>", {
type: "text",
name: "productPrice",
class: "form-control",
id: obj.productName + "Id",
value: obj.productPrice
});
試試上面的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.