양식 제출 후 Jquery 콜백을 수행하는 방법은 무엇입니까?
remote = true로 간단한 양식이 있습니다.
이 양식은 실제로 HTML 대화 상자에 있으며 제출 단추를 클릭하자마자 닫힙니다.
이제 양식이 성공적으로 제출 된 후 기본 HTML 페이지를 약간 변경해야합니다.
나는 jQuery를 사용하여 이것을 시도했다. 그러나 이렇게하면 양식 제출에 대한 일부 형식의 응답 후에 작업을 수행 할 수 없습니다.
$("#myform").submit(function(event) {
// do the task here ..
});
양식이 성공적으로 제출 된 후에 만 코드가 실행되도록 콜백을 어떻게 첨부합니까? .success 또는 .complete 콜백을 양식에 추가하는 방법이 있습니까?
방금 했어요-
$("#myform").bind('ajax:complete', function() {
// tasks to do
});
그리고 일이 완벽하게 작동했습니다.
자세한 내용은 이 API 설명서 를 참조하십시오.
신뢰할 수있는 최고의 솔루션을 얻지 못했지만이 효과를 발견했습니다. 그것이 필요한지 확실하지 않지만 태그에 action 또는 method 속성이 없으므로 $ .ajax 함수가 POST를 처리하고 콜백 옵션을 제공합니다.
<form id="form">
...
<button type="submit"></button>
</form>
<script>
$(document).ready(function() {
$("#form_selector").submit(function() {
$.ajax({
type: "POST",
url: "form_handler.php",
data: $(this).serialize(),
success: function() {
// callback code here
}
})
})
})
</script>
서버에 대한 AJAX 호출을 통해 수동으로 작업을 수행해야합니다. 양식을 재정의해야합니다.
그러나 걱정하지 마십시오. 그것은 케이크 조각입니다. 양식 작업에 대한 개요는 다음과 같습니다.
- 기본 제출 조치를 대체하십시오 (
preventDefault
메소드 가있는 전달 된 이벤트 오브젝트 덕분에 ) - 양식에서 필요한 모든 값을 가져옵니다
- HTTP 요청 발생
- 요청에 대한 응답을 처리
먼저 다음과 같이 양식 제출 작업을 취소해야합니다.
$("#myform").submit(function(event) {
// Cancels the form's submit action.
event.preventDefault();
});
And then, grab the value of the data. Let's just assume you have one text box.
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
});
And then fire off a request. Let's just assume it's a POST request.
$("#myform").submit(function(event) {
event.preventDefault();
var val = $(this).find('input[type="text"]').val();
// I like to use defers :)
deferred = $.post("http://somewhere.com", { val: val });
deferred.success(function () {
// Do your stuff.
});
deferred.error(function () {
// Handle any errors here.
});
});
And this should about do it.
Note 2: For parsing the form's data, it's preferable that you use a plugin. It will make your life really easy, as well as provide a nice semantic that mimics an actual form submit action.
Note 2: You don't have to use defers. It's just a personal preference. You can equally do the following, and it should work, too.
$.post("http://somewhere.com", { val: val }, function () {
// Start partying here.
}, function () {
// Handle the bad news here.
});
For MVC here was an even easier approach. You need to use the Ajax form and set the AjaxOptions
@using (Ajax.BeginForm("UploadTrainingMedia", "CreateTest", new AjaxOptions() { HttpMethod = "POST", OnComplete = "displayUploadMediaMsg" }, new { enctype = "multipart/form-data", id = "frmUploadTrainingMedia" }))
{
... html for form
}
here is the submission code, this is in the document ready section and ties the onclick event of the button to to submit the form
$("#btnSubmitFileUpload").click(function(e){
e.preventDefault();
$("#frmUploadTrainingMedia").submit();
});
here is the callback referenced in the AjaxOptions
function displayUploadMediaMsg(d){
var rslt = $.parseJSON(d.responseText);
if (rslt.statusCode == 200){
$().toastmessage("showSuccessToast", rslt.status);
}
else{
$().toastmessage("showErrorToast", rslt.status);
}
}
in the controller method for MVC it looks like this
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult UploadTrainingMedia(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// there is only one file ... do something with it
}
return Json(new
{
statusCode = 200,
status = "File uploaded",
file = "",
}, "text/html");
}
else
{
return Json(new
{
statusCode = 400,
status = "Unable to upload file",
file = "",
}, "text/html");
}
}
I do not believe there is a callback-function like the one you describe.
What is normal here is to do the alterations using some server-side language, like PHP.
In PHP you could for instance fetch a hidden field from your form and do some changes if it is present.
PHP:
$someHiddenVar = $_POST["hidden_field"];
if (!empty($someHiddenVar)) {
// do something
}
One way to go about it in Jquery is to use Ajax. You could listen to submit, return false to cancel its default behaviour and use jQuery.post() instead. jQuery.post has a success-callback.
$.post("test.php", $("#testform").serialize(), function(data) {
$('.result').html(data);
});
http://api.jquery.com/jQuery.post/
The form's "on submit" handlers are called before the form is submitted. I don't know if there is a handler to be called after the form is submited. In the traditional non-Javascript sense the form submission will reload the page.
$("#formid").ajaxForm({ success: function(){ //to do after submit } });
참고URL : https://stackoverflow.com/questions/11534690/how-to-do-a-jquery-callback-after-form-submit
'development' 카테고리의 다른 글
Python으로 ssh를 통해 명령 수행 (0) | 2020.07.27 |
---|---|
일치하지 않는 익명의 define () 모듈 (0) | 2020.07.26 |
JNA 대신 JNI를 사용하여 기본 코드를 호출 하시겠습니까? (0) | 2020.07.26 |
루비 : 자기 확장 (0) | 2020.07.26 |
nodejs를 사용하여 기본 브라우저를 열고 특정 URL로 이동하는 방법 (0) | 2020.07.26 |