我正在提交一份需要前往两个不同地点的表格。隐藏表单并使用jquery .val
方法自动填充。我如何编写ajax以在2个不同的位置提交?如果我无法访问服务器端设置,是否可以执行此操作?
以下是我提交的表单
<form action="x" method="post" class="form-inline">
<input type="hidden" name="players_name" class="form-control" id="playersFullName_submit">
<input type="hidden" name="players_email"class="form-control" id="playersEmail_submit">
<input type="hidden" name="players_score" class="form-control" id="playersScore_submit">
<input type="hidden" name="redirect_url" class="form-control" id="redirectURL_submit" value="x">
<input id="submit endGame" type="submit" class="btn btn-default" value="Submit Your Score">
</form>
这是我的jquery填写
$(function () { // fill form fields
$('#playersFullName_submit').val(playersFullName);
$('#p_name').append(playersFullName);
$('#playersEmail_submit').val(playersEmail);
$('#dateSubmitted').val(submitDate);
});
以下是我认为我需要设置的方式
$.ajax({
type: "POST",
url : "url1.com",
data: {},
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: {},
success: function(msg){
// get response here
}
});
我是否需要在数据中输入任何内容,还是将其从<form>
答案 0 :(得分:1)
您需要获取表单数据并将其注入data
属性中的AJAX调用。您可以使用JQuery的 serialize()
method :
// Get your reference to the form:
var theForm = document.getElementsByTagName("form")[0];
$.ajax({
type: "POST",
url : "url1.com",
data: $(theForm).serialize(), // <-- Inject serialized form data
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: $(theForm).serialize(), // <-- Inject serialized form data
success: function(msg){
// get response here
}
});
答案 1 :(得分:0)
b / c你提交ajax而不是表单,你需要阻止表单表单操作提交,而是在ajax中声明你的服务器端路由。
$('#submit_btn').on('click', function(e) {
e.preventDefault(); // you need this so the form don't submit
$.ajax({
type: "POST",
url : "url1.com",
data: {},
success: function(msg1){
var msg1;
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: {},
success: function(msg2){
var msg2;
}
});
});
答案 2 :(得分:0)
$.ajax({
type: "POST",
url : "url1.com",
data: $('.form-inline').serialize(),
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: $('.form-inline').serialize(),
success: function(msg){
// get response here
}
});
答案 3 :(得分:0)
如果您必须发现自己必须发送到许多网址...
var theForm = document.getElementsByTagName("form")[0],
urls = ['url1.com','url2.com', ....];
$.each(urls, function(index,value){
$.ajax({
type: "POST",
url : value,
data: $(theForm).serialize(),
success: function(msg){
// get response here
}
});
});