Last active
August 21, 2018 12:59
-
-
Save darolo/5cc5a21b44e8971cf1f482d4737f4ebb to your computer and use it in GitHub Desktop.
LinkWithDataPost
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(factory){ | |
if ( typeof define === 'function' && define.amd ) { | |
// AMD. Register as an anonymous module. | |
define(factory); | |
} else if (typeof exports === 'object') { | |
// Node/CommonJS style for Browserify | |
module.exports = factory; | |
} else { | |
// Browser globals | |
factory(); | |
} | |
}(function(undefined){ | |
var links = document.querySelectorAll('a[data-post]'), | |
links_length = links.length, | |
link; | |
for(var i = 0; i < links_length; i += 1){ | |
link = links[i]; | |
link.addEventListener('click', function(e){ | |
e.preventDefault(); | |
var data_post_atrribute = this.getAttribute("data-post"), | |
data_post = {}, | |
form = document.createElement("form"); | |
form.setAttribute("method", 'post'); | |
form.setAttribute("action", this.href); | |
data_post_atrribute.replace(/([^;&]+)[=:]+([^;&]+)/g, | |
function(match, key, value, begin, fullstring){ data_post[key] = value; }); | |
for(var key in data_post){ | |
form.appendChild(function(){ | |
var hiddenField = document.createElement("input"); | |
hiddenField.setAttribute("type", "hidden"); | |
hiddenField.setAttribute("name", key); | |
hiddenField.setAttribute("value", data_post[key]); | |
return hiddenField; | |
}()); | |
} | |
document.body.appendChild(form); | |
form.submit(); | |
}); | |
} | |
})); // End |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment