Skip to content

Instantly share code, notes, and snippets.

@kanghyojun
Last active May 24, 2018 06:26
Show Gist options
  • Select an option

  • Save kanghyojun/5982382 to your computer and use it in GitHub Desktop.

Select an option

Save kanghyojun/5982382 to your computer and use it in GitHub Desktop.
/* make HTML Form RESTful!!
Usage
======
..
<form action="/user/" method="PUT" id="userForm">
<input type="text" name="id" />
...
<input type="submit" value="edit" />
</form>
<script type="text/javascript">
$('#userForm').restfulize({
'success': function(d) {
console.log(d);
},
'error': function(j, q, x) {
console.log(j, q, x);
},
'header': {
'Content-Type': 'application/json'
}
})
</script>
*/
$.fn.extend({
restfulize: function(options) {
this.submit(function(e) {
var $this = $(this),
v = $this.serializeArray();
json = {}
for(i in v) {
var item = v[i]
json[item.name] = item.value;
}
$.ajax({
'type': $this.attr('method'),
'url': $this.attr('action'),
'data': JSON.stringify(json),
'dataType': 'json',
'headers': options['headers'],
'success': options['success'],
'error': options['error']
});
return false;
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment