Domanda

Ho il seguente codice:

<script type="text/javascript">
        function SubmitForm()
        {

            form1.submit();
        }

        function ShowResponse()
        {

        }
</script>
.
.
.
<div>
    <a href="#" onclick="SubmitForm();">Click</a>
</div>

Voglio catturare il codice html di risposta di form1.submit?Come faccio a fare questo?Posso registrare qualsiasi funzione di callback a form1.metodo di invio?

È stato utile?

Soluzione

Non sarà in grado di farlo facilmente con javascript pianura. Quando pubblichi un modulo, gli ingressi del modulo vengono inviati al server e la vostra pagina viene aggiornata - i dati vengono trattati sul lato server. Cioè, la funzione submit() in realtà non restituisce nulla, semplicemente invia i dati del modulo al server.

Se si voleva davvero per ottenere la risposta in Javascript (senza la pagina rinfrescante), allora avrete bisogno di utilizzare AJAX, e quando si comincia a parlare utilizzando AJAX, ti necessità per utilizzare una libreria. jQuery è di gran lunga il più popolare, e il mio preferito. C'è un ottimo plugin per jQuery chiamato modulo che farà esattamente quello che suona come si desidera.

Ecco come usereste jQuery e che plug-in:

$('#myForm')
    .ajaxForm({
        url : 'myscript.php', // or whatever
        dataType : 'json',
        success : function (response) {
            alert("The server says: " + response);
        }
    })
;

Altri suggerimenti

Un'alternativa Ajax è quello di impostare un <iframe> invisibile come bersaglio del vostro modulo e leggere il contenuto di tale <iframe> nel suo gestore onload. Ma perché preoccuparsi quando non c'è l'Ajax?

Nota. Volevo solo parlare di questa alternativa dal momento che alcune delle risposte sostengono che si tratta di impossibile per raggiungere questo obiettivo senza Ajax

Lo sto facendo in questo modo e il suo funzionamento.

$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(){
        console.log('form submitted.');
      }
    });
    return false;
});

Il non-jQuery modo, estratto da 12me21 commento:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/your/url/name.php"); 
xhr.onload = function(event){ 
    alert("Success, server responded with: " + event.target.response); // raw response
}; 
// or onerror, onabort
var formData = new FormData(document.getElementById("myForm")); 
xhr.send(formData);

Per POST's il tipo di contenuto predefinito è "application/x-www-form-urlencoded", che corrisponde a ciò che stiamo inviando in questo frammento di codice.Se si desidera inviare "altre cose" o modificarlo in qualche modo vedere qui per alcuni minimi dettagli.

Non sono sicuro che si capisce che cosa submit () fa ...

Quando si esegue form1.submit(); le informazioni formulario viene inviato al server web.

Il WebServer farà tutto suo deve fare e restituire una nuova pagina Web al client (di solito la stessa pagina con qualcosa è cambiato).

Quindi, non c'è modo è possibile "catturare" il ritorno di un'azione form.submit ().

Internet del futuro ricercatori:

Per i nuovi browser (come del 2018: Chrome, Firefox, Safari, Opera, Riva, e la maggior parte dei browser mobili, ma non IE), fetch è un'API standard che semplifica le chiamate di rete asincrona (per che abbiamo usato per bisogno di XMLHttpRequest o $.ajax di jQuery).

Qui è una forma tradizionale:

<form id="myFormId" action="/api/process/form" method="post">
    <!-- form fields here -->
    <button type="submit">SubmitAction</button>
</form>

Se un modulo come sopra viene consegnato a voi (o si è creato perché è HTML semantica), allora si può avvolgere il codice fetch in un listener di eventi, come di seguito:

document.forms['myFormId'].addEventListener('submit', (event) => {
    event.preventDefault();
    // TODO do something here to show user that form is being submitted
    fetch(event.target.action, {
        method: 'POST',
        body: new URLSearchParams(new FormData(event.target)) // event.target is the form
    }).then((resp) => {
        return resp.json(); // or resp.text() or whatever the server sends
    }).then((body) => {
        // TODO handle body
    }).catch((error) => {
        // TODO handle error
    });
});

(o, se come il manifesto originale che si desidera chiamare manualmente senza un evento di presentare, appena messo il codice fetch lì e passare un riferimento all'elemento form invece di utilizzare event.target.)

Documenti:

Fetch: https://developer.mozilla.org/en-US/docs/Web / API / Fetch_API

Altro: https://developer.mozilla.org/en-US/docs / Imparare / HTML / Forme / Sending_forms_through_JavaScript Quella pagina nel 2018 non menziona fetch (ancora). Ma afferma che il target = trucco "myIFrame" è deprecato. E ha anche un esempio di form.addEventListener per l'evento 'Invia'.

Non v'è alcun callback. E 'come seguendo un link.

Se si desidera catturare la risposta del server, usare AJAX o per posta ad un Iframe e afferrare quello che sembra lì dopo evento onload() del iframe.

È possibile event.preventDefault() nel gestore di click per il pulsante di invio per garantire che il modulo HTML evento di default submit non si attiva (che è ciò che porta alla pagina di rinfrescante).

Un'altra alternativa sarebbe quella di utilizzare forma hackier markup: E 'l'uso di <form> e type="submit" che sta ottenendo nel modo del comportamento desiderato qui; in quanto questi alla fine porterà a cliccare eventi aggiornare la pagina.

Se si desidera utilizzare ancora <form>, e non si vuole scrivere personalizzato cliccare gestori, è possibile utilizzare il metodo ajax di jQuery, che astrae l'intero problema via per voi esponendo metodi promessa per success, error, ecc


Per ricapitolare, è possibile risolvere il problema sia:

• prevenire comportamenti di default nella funzione di gestione utilizzando event.preventDefault()

• utilizzando elementi che non hanno un comportamento di default (ad esempio <form>)

• utilizzando jQuery ajax


(ho appena notato questa domanda è a partire dal 2008, non so perché si presentò nel mio feed; in ogni caso, speriamo che questo è una risposta chiara)

    $.ajax({
        url: "/users/login/",    //give your url here
        type: 'POST',
        dataType: "json",
        data: logindata,
        success: function ( data ){
        //  alert(data);    do your stuff
        },
        error: function ( data ){
        //  alert(data);    do your stuff
        }
    });

Questo è il mio codice per questo problema:

<form id="formoid" action="./demoText.php" title="" method="post">
    <div>
        <label class="title">First Name</label>
        <input type="text" id="name" name="name" >
    </div>
    <div>
        <input type="submit" id="submitButton"  name="submitButton" value="Submit">
    </div>
</form>

<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $( this ), url = $form.attr( 'action' );

  /* Send the data using post with element id name and name2*/
  var posting = $.post( url, { name: $('#name').val()} );

  /* Alerts the results */
  posting.done(function( data ) {
    alert('success');
  });
});
</script>

Nel caso in cui si desidera catturare l'uscita di una richiesta AJAX utilizzando Chrome è possibile seguire questi semplici passi:

  1. Aprire la casella degli strumenti programmatori
  2. Vai alla console e destro in qualsiasi punto all'interno che
  3. Nel menu che appare, cliccare su "Attiva XMXHTTPRequest Logging"
  4. Dopo aver fatto che ogni volta che si effettua una richiesta AJAX un messaggio che inizia con "XHR carico finito: http: // ......". Apparirà nella vostra console
  5. Cliccando sul link che appare, porterà la "scheda Risorse" in cui il vostro grado di vedere le intestazioni e il contenuto della risposta!

Sulla base della risposta da @rajesh_kw ( https://stackoverflow.com/a/22567796/4946681 ), ho gestire gli errori sotto forma postali e di successo:

    $('#formName').on('submit', function(event) {
        event.preventDefault(); // or return false, your choice
        $.ajax({
            url: $(this).attr('action'),
            type: 'post',
            data: $(this).serialize(),
            success: function(data, textStatus, jqXHR) {
                // if success, HTML response is expected, so replace current
                if(textStatus === 'success') {
                    // https://stackoverflow.com/a/1236378/4946681
                    var newDoc = document.open('text/html', 'replace');
                    newDoc.write(data);
                    newDoc.close();
                }
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            if(jqXHR.status == 0 || jqXHR == 302) {
                alert('Your session has ended due to inactivity after 10 minutes.\nPlease refresh this page, or close this window and log back in to system.');
            } else {
                alert('Unknown error returned while saving' + (typeof errorThrown == 'string' && errorThrown.trim().length > 0 ? ':\n' + errorThrown : ''));
            }
        });
    });

Faccio uso di this in modo che la mia logica è riutilizzabile, mi aspetto HTML da restituire in un successo così ho renderlo e sostituire la pagina corrente, e nel mio caso mi aspetto un redirect alla pagina di login se la sessione è scaduta, quindi mi intercetta che reindirizza al fine di preservare lo stato della pagina.

Ora gli utenti possono accedere tramite un'altra scheda e provare la loro inviare nuovamente.

È necessario utilizzare AJAX. L'invio del modulo di solito si traduce nel browser il caricamento di una nuova pagina.

È possibile farlo utilizzando JavaScript e la tecnologia AJAX. Date un'occhiata a jQuery e, a questo . Hai solo bisogno di includere due file js registrare un callback per il form.submit.

È possibile eseguire questa operazione utilizzando jQuery e la metodo nofollow ajax() :

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function submitform() {
      $.ajax({
        headers: { 
          'Accept': 'application/json',
          'Content-Type': 'application/json' 
        },
        type: "POST",
        url : "/hello.hello",
        dataType : "json",
        data : JSON.stringify({"hello_name": "hello"}),
        error: function () {
          alert('loading Ajax failure');
        },
    	onFailure: function () {
          alert('Ajax Failure');
    	},
    	statusCode: {
          404: function() {
          alert("missing info");
          }   
    	},
        success : function (response) {
          alert("The server says: " + JSON.stringify(response));
        }
      })
      .done(function( data ) {
        $("#result").text(data['hello']);
      });
};</script>

 $(document).ready(function() {
    $('form').submit(function(event) {
        event.preventDefault();
        $.ajax({
            url : "<wiki:action path='/your struts action'/>",//path of url where u want to submit form
            type : "POST",
            data : $(this).serialize(),
            success : function(data) {
                var treeMenuFrame = parent.frames['wikiMenu'];
                if (treeMenuFrame) {
                    treeMenuFrame.location.href = treeMenuFrame.location.href;
                }
                var contentFrame = parent.frames['wikiContent'];
                contentFrame.document.open();
                contentFrame.document.write(data);
                contentFrame.document.close();
            }
        });
    });
});
  

Blockquote

firrst del tutto l'uso .ready (function ()) $ (document) all'interno di questo uso ( 'formid'). Presentare (function (evento)) e quindi prevenire l'azione predefinita aftyer quella forma chiamata AJAX presentazione $ .Ajax ({,,,,}); ci vorrà parametro u può scegliere secondo il vostro requisito quindi chiamare AFunction successo: funzione (dati) { // fare quello che vuoi il mio esempio per mettere html risposta sul div}

Prima di tutto abbiamo bisogno di serializeObject();

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

poi si crea una base post e ottenere risposta

$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) {
if(data){
//do true 
}
else
{
//do false
}

});

Ho seguito il codice perfactly eseguito utilizzando Ajax con i dati del modulo a più parti

function getUserDetail()
{
    var firstName = document.getElementById("firstName").value;
    var lastName = document.getElementById("lastName").value;
    var username = document.getElementById("username").value;
    var email = document.getElementById("email").value;
    var phoneNumber = document.getElementById("phoneNumber").value;
    var gender =$("#userForm input[type='radio']:checked").val();
    //var gender2 = document.getElementById("gender2").value;
    //alert("fn"+firstName+lastName+username+email);
    var roleIndex = document.getElementById("role");
    var role = roleIndex.options[roleIndex.selectedIndex].value;
    var jobTitleIndex = document.getElementById("jobTitle");
    var jobTitle = jobTitleIndex.options[jobTitleIndex.selectedIndex].value;
    var shiftIdIndex = document.getElementById("shiftId");
    var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value;


    var addressLine1 = document.getElementById("addressLine1").value;
    var addressLine2 = document.getElementById("addressLine2").value;
    var streetRoad = document.getElementById("streetRoad").value;

    var countryIndex = document.getElementById("country");
    var country = countryIndex.options[countryIndex.selectedIndex].value;

    var stateIndex = document.getElementById("state");
    var state = stateIndex.options[stateIndex.selectedIndex].value;

    var cityIndex = document.getElementById("city");
    var city = cityIndex.options[cityIndex.selectedIndex].value;



    var pincode = document.getElementById("pincode").value;

    var branchIndex = document.getElementById("branch");
    var branch = branchIndex.options[branchIndex.selectedIndex].value;

    var language = document.getElementById("language").value;
    var profilePicture = document.getElementById("profilePicture").value;
    //alert(profilePicture);
    var addDocument = document.getElementById("addDocument").value;


    var shiftIdIndex = document.getElementById("shiftId");
    var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value;


    var data = new FormData();
    data.append('firstName', firstName);
    data.append('lastName', lastName);
    data.append('username', username);
    data.append('email', email);
    data.append('phoneNumber', phoneNumber);
    data.append('role', role);
    data.append('jobTitle', jobTitle);
    data.append('gender', gender);
    data.append('shiftId', shiftId);
    data.append('lastName', lastName);
    data.append('addressLine1', addressLine1);
    data.append('addressLine2', addressLine2);
    data.append('streetRoad', streetRoad);
    data.append('country', country);
    data.append('state', state);
    data.append('city', city);
    data.append('pincode', pincode);
    data.append('branch', branch);
    data.append('language', language);
    data.append('profilePicture', $('#profilePicture')[0].files[0]);
     for (var i = 0; i < $('#document')[0].files.length; i++) {
            data.append('document[]', $('#document')[0].files[i]);
        }



    $.ajax({
        //url : '${pageContext.request.contextPath}/user/save-user',
        type: "POST",
        Accept: "application/json",
        async: true,
        contentType:false,
        processData: false,
        data: data,
        cache: false,

        success : function(data) {      
            reset();
            $(".alert alert-success alert-div").text("New User Created Successfully!");
         },
       error :function(data, textStatus, xhr){
           $(".alert alert-danger alert-div").text("new User Not Create!");
        }


    });


//

}

È possibile utilizzare jQuery.post () e restituire risposte JSON ben strutturati dal server . Consente inoltre di convalidare / sterilizzare i dati direttamente sul server, che è una buona pratica, perché è più sicuro (e ancora più facile) che facendo questo sul client.

Per esempio, se avete bisogno di inviare modulo HTML al server (a saveprofilechanges.php) con i dati utente per semplice registrazione:

I. parti client:

I.a. parte HTML:

<form id="user_profile_form">
  <label for="first_name"><input type="text" name="first_name" id="first_name" required />First name</label>
  <label for="family_name"><input type="text" name="family_name" id="family_name" required />Family name</label>
  <label for="email"><input type="email" name="email" id="email" required />Email</label> 
  <input type="submit" value="Save changes" id="submit" />
</form>

I.B. parte Script:

$(function () {
    $("#user_profile_form").submit(function(event) {
      event.preventDefault();
      var postData = {
        first_name: $('#first_name').val(),
        family_name: $('#family_name').val(),
        email: $('#email').val()
      };
      $.post("/saveprofilechanges.php", postData,
        function(data) {
          var json = jQuery.parseJSON(data);
          if (json.ExceptionMessage != undefined) {
            alert(json.ExceptionMessage); // the exception from the server
            $('#' + json.Field).focus(); // focus the specific field to fill in
          }
          if (json.SuccessMessage != undefined) {
            alert(json.SuccessMessage); // the success message from server
          }
       });
    });
});

II. parte server (saveprofilechanges.php):

$data = $_POST;
if (!empty($data) && is_array($data)) {
    // Some data validation:
    if (empty($data['first_name']) || !preg_match("/^[a-zA-Z]*$/", $data['first_name'])) {
       echo json_encode(array(
         'ExceptionMessage' => "First name missing or incorrect (only letters and spaces allowed).",
         'Field' => 'first_name' // Form field to focus in client form
       ));
       return FALSE;
    }
    if (empty($data['family_name']) || !preg_match("/^[a-zA-Z ]*$/", $data['family_name'])) {
       echo json_encode(array(
         'ExceptionMessage' => "Family name missing or incorrect (only letters and spaces allowed).",
         'Field' => 'family_name' // Form field to focus in client form
       ));
       return FALSE;
    }
    if (empty($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
       echo json_encode(array(
         'ExceptionMessage' => "Email missing or incorrectly formatted. Please enter it again.",
         'Field' => 'email' // Form field to focus in client form
       ));
       return FALSE;
    }
    // more actions..
    // more actions..
    try {
       // Some save to database or other action..:
       $this->User->update($data, array('username=?' => $username));
       echo json_encode(array(
         'SuccessMessage' => "Data saved!"
       ));
       return TRUE;
    } catch (Exception $e) {
       echo json_encode(array(
         'ExceptionMessage' => $e->getMessage()
       ));
       return FALSE;
    }
}

è possibile farlo senza Ajax.

scrivere il come qui di seguito.

.. .. ..

e poi in "action.php"

poi dopo frmLogin.submit ();

leggi $ submit_return variabile ..

$ submit_return contiene il valore di ritorno.

buona fortuna.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top