2017-05-26 4 views
0

Ich versuche, meine Formulardaten zu meiner API zu veröffentlichen. Während ich anrufen kann, sieht es so aus, als würden keine Daten gepostet.Nicht in der Lage, Daten an meine Web-API zu senden - Ajax

Was mache ich falsch? Außerdem möchte ich die Daten im JSON-Format veröffentlichen. Soll ich JSON.stringify() machen?

P.S. Noob Hier

<div id="response"> 
    <pre></pre> 
</div> 

<form id="my-form"> 
      <div id="app"> 
      <h1 style="color:#5bb7db;">Get Started</h1> 
      <div class="form-group"> 
       <label for="src">Source:</label> 
       <input type="text" class="form-control" id="src" placeholder="source folder path"> 
      </div> 
      <div class="form-group"> 
       <label for="dest">Destination:</label> 
       <input type="text" class="form-control" id="dest" placeholder="destination folder path"> 
      </div> 
      <button type="submit" id="sbmt" class="btn btn-primary">Submit</button> 
</form> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script> 
    (function($){ 
     function processForm(e){ 
     console.log($(this).serialize()); 
      $.ajax({ 
       url: 'http://localhost:3000/posts', 
       dataType: 'text', 
       type: 'post', 
       cors: true, 
       contentType: 'application/json', 
       data: $(this).serialize(), 
       success: function(data, textStatus, jQxhr){ 
        $('#response pre').html(data); 
       }, 
       error: function(jqXhr, textStatus, errorThrown){ 
        console.log(errorThrown); 
       } 
      }); 

      e.preventDefault(); 
     } 

     $('#my-form').submit(processForm); 
    })(jQuery); 
</script> 
</body> 

Antwort

0

Sie müssen Namen einzustellen für source und destination Eingänge

<input type="text" name="source" class="form-control" id="src" placeholder="source folder path"> 

<input type="text" name="destination" class="form-control" id="dest" placeholder="destination folder path"> 
+0

Danke. das funktioniert. Wie konvertiere ich meine Formulardaten in ein JSON-Format? –

+0

Ich versuche, eine {Quelle: $ ('# Quelle'). Val(), Ziel: $ ('# Ziel'). Val()} aber ich bekomme {Quelle: undefined, Ziel: undefined} –

+0

Um in ein JSON zu konvertieren, müssen Sie 'serializeArray' wie folgt 'var data = JSON.stringify ($ (this) .serializeArray());' –

Verwandte Themen