我不想每次都写一个ajax调用,因为我的API URL,post方法和表单id或类名将根据页面改变,所以我试图创建一个自定义函数来处理API调用尊重传递的参数。 并且必需参数是传递形式id,帖子类型,URL,数据......等等。
$("#contactForm").submit(function(e) {
var url = "https://api.sample.com/V2.0/apinamewillchange"; // the script where you handle the form input.
$.ajax({
//crossDomain: true,
type: "POST",
url: url,
data: $("#contactForm").serialize(), // serializes the form's elements.
success: function(data)
{
var loginresponse = data;
console.log(loginresponse); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
以及我希望如何创建,不仅仅是我试过的一些东西
function customRequest(postype,url,data,formid) {
$(formid).submit(function(e) {
var promise = $.ajax({
type: t,
data: d,
url: u
})
return promise;
}
}
答案 0 :(得分:1)
关注此
这个函数调用你的自定义ajax并传递你想要的ajax属性,如(url,方法类型,数据,回调等)
function sendAJax1() {
var type = "POST";
var url = "https://api.sample.com/V2.0/ajax1.php";
var data = $("#form1").serialize();
var formid = "#form1";
customRequest(type, url, data, formid, function(data) {
// do something with your ajax callback
} );
}
function sendAJax2() {
var type = "POST";
var url = "https://api.sample.com/V2.0/ajax2.php";
var data = $("#form2").serialize();
var formid = "#form2";
customRequest(type, url, data, formid, function(data) {
// do something with your ajax callback
} );
e.preventDefault(); // avoid
}
此函数读取指定表单的提交事件,并发送指定它的urj请求(url,方法类型,数据,回调等)
function customRequest(postype, url, data, formid, callback) {
$(formid).on('submit', function(e) {
$.ajax({
//crossDomain: true,
type: postype,
url: url,
data: data, // serializes the form's elements.
success: function(data) {
return callback(data);
}
});
e.preventDefault(); // avoid
})
}