我正在尝试将HTML
表单数据转换为JSON
对象,我有这个线程,但我不知道为什么它不适合我。我正在使用以下代码。
<form id="myform" action="" method="post">
<div class="form-field">
<label for="title">Title</label>
<input name="title" id="title" type="text" value="" size="40" aria-required="true">
</div>
<div class="form-field form-required">
<label for="your-name">Your Name</label>
<input name="yourName" id="yourName" type="text" value="" size="40" aria-required="true">
</div>
<div class="form-field">
<label for="contact-no">Contact No:</label>
<input name="contact" id="contact" type="text" value="" size="40" aria-required="true">
</div>
<div class="form-field">
<label for="description">Description:</label>
<textarea name="description" id="description" rows="1" cols="40" aria-required="true"></textarea>
</div>
<div class="form-field">
<label for="email">Email:</label>
<input name="email" id="email" type="text" value="optional" size="40" aria-required="true">
</div>
<div class="form-field">
<label for="city">City:</label>
<input name="city" id="city" type="text" value="" size="40" aria-required="true">
</div>
<div class="form-field">
<label for="country">Country:</label>
<input name="country" id="country" type="text" value="" size="40" aria-required="true">
</div>
<div class="form-field">
<label for="pic1">Picture 1:</label>
<input type="file" name="pic1" id="pic1">
</div>
<div class="form-field">
<label for="pic2">Picture 2:</label>
<input type="file" name="pic2" id="pic2">
</div>
<div class="form-field">
<label for="pic3">Picture 3:</label>
<input type="file" name="pic3" id="pic3">
</div>
<div class="form-field">
<label for="pic4">Picture 4:</label>
<input type="file" name="pic4" id="pic4">
</div>
<div class="form-field">
<label for="pic5">Picture 5:</label>
<input type="file" name="pic5" id="pic5">
</div>
<div class="form-field">
<label for="demand">Your Demand:</label>
<input name="demand" id="demand" type="text" value="" size="40" aria-required="true">
</div>
<p class="submit">
<input type="submit" name="postAd" id="postAd" class="button" value="Post Ad For Review">
</p>
<div id="results">hello</div>
</form>
$(document).ready(function(){
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] === undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
alert(this.name);
o[this.name] = this.value || '';
}
});
return o;
};
$('#myform').submit(function() {
$('#result').text(JSON.stringify($('#myform').serializeObject()));
return false;
});
});
我试图调试它,我注意到当我的函数运行时,它总是运行 else 语句中的代码。