0
我想發佈我的表單數據到我的API。雖然我可以撥打電話,但看起來沒有數據發佈。無法發佈數據到我的網頁api - ajax
我在做什麼錯?另外,我想以JSON格式發佈數據。我應該做JSON.stringify()嗎?
P.S.小白這裏
<div id="response">
<pre></pre>
</div>
<form id="my-form">
<div id="app">
<h1 style="color:#5bb7db;">Get Started</h1>
<div class="form-group">
<label for="src">Source:</label>
<input type="text" class="form-control" id="src" placeholder="source folder path">
</div>
<div class="form-group">
<label for="dest">Destination:</label>
<input type="text" class="form-control" id="dest" placeholder="destination folder path">
</div>
<button type="submit" id="sbmt" class="btn btn-primary">Submit</button>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function($){
function processForm(e){
console.log($(this).serialize());
$.ajax({
url: 'http://localhost:3000/posts',
dataType: 'text',
type: 'post',
cors: true,
contentType: 'application/json',
data: $(this).serialize(),
success: function(data, textStatus, jQxhr){
$('#response pre').html(data);
},
error: function(jqXhr, textStatus, errorThrown){
console.log(errorThrown);
}
});
e.preventDefault();
}
$('#my-form').submit(processForm);
})(jQuery);
</script>
</body>
謝謝集名稱。這樣可行。如何將我的表單數據轉換爲JSON格式? –
我試圖做一個 {source:$('#source')。val(),destination:$('#destination')。 undefined} –
要轉換成JSON,你需要'serializeArray'像這樣'var data = JSON.stringify($(this).serializeArray());' –