我想使用scala模板重用一个javascript函数,所以我只需要传递一个不同的成功/失败函数,但我似乎无法将一个javascript函数传递给scala模板。 请注意我是新手,甚至不知道我在做什么是可能的。
这就是我想要实现的目标:
@(formId: String, success: JavaScript, fail: JavaScript)
<script type="text/javascript">
$("@formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
@success()
/*console.log("save succesfull, progress!")
alert('Save successfull, now move on!');*/
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
//if fails
@fail()
/*console.log(jqXHR.responseText);
var errors = JSON.parse(jqXHR.responseText);
console.log(errors);
alert('Woops, something went wrong: ' + jqXHR.responseText);*/
}
});
e.preventDefault();
});
</script>
如何使用:
@snippets.ajaxFormSubmit("#form",
function()
{
alert("Save successfull, now move on!");
},
function()
{
alert("Save failed!");
}
)
答案 0 :(得分:1)
您可以通过 Html 类型将任何内容传递给模板。
@(formId: String, success: Html, fail: Html)
<script type="text/javascript">
$("@formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
@success
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
@fail
}
});
e.preventDefault();
});
</script>
在客户端视图中,您可以按如下方式使用它:
@successFunc = {
alert("Save successfull, now move on!");
}
@failureFunc = {
alert("Save failed!");
}
@snippets.ajaxFormSubmit("#form", successFunc, failureFunc)