Use AJAX to send html5 textarea directly without html <form>

后端 未结 3 2016
梦如初夏
梦如初夏 2020-12-17 03:11

Recently I am confused about whether it\'s possible to send input/textarea data directly without being included in html

. I thought in web page, if
相关标签:
3条回答
  • 2020-12-17 03:13

    Perhaps your reviewer was referring to the HTML5 textarea attribute "form". It allows a textarea to be part of a specified form without being inside the form element. http://www.w3schools.com/tags/att_textarea_form.asp

    But generally speaking, as long as you can identify an element, say a textarea, you can access the text inside it and send it to the server without submitting any forms using ajax. From Sable's comment:
    http://api.jquery.com/jquery.post OR http://api.jquery.com/jquery.ajax/

    0 讨论(0)
  • 2020-12-17 03:20

    Yes, you can submit data to a server without putting it into a form. Form's provide a simpler mechanism for sending larger amounts of data to a server without the developer having to tell the browser how to encode the form.

    EG:

    HTML

    JS

    var text = $("input[type='text']").val();
    $.post("/my/server/url", { userInput : text }, function(data){ /* Success! */});
    

    This would technically post the data to the server without a form.

    0 讨论(0)
  • 2020-12-17 03:21

    Ajax (Asynchronous Javascript & XML) is a way to send data from client to the server asynchronously. For that you'd have to write code for sending the data in the client-side using Javascript/HTML and also to process the received data using server-side languages (eg PHP) on the server-side.

    And, yes you don't need a <form> tag to do so.

    Check out this example.

    HTML:

    <label>Text</label>
    <textarea id="foo"></textarea>
    
    <button id="submit">Submit via Ajax</button>
    

    Javascript:

    $('#submit').click(function(e) {
        e.preventDefault();
    
        // information to be sent to the server
        var info = $('#foo').val();
    
        $.ajax({
            type: "POST",
            url: 'server.php',
            data: {foo: info}
        });
    });
    

    Server-side Handler (PHP): server.php

    <?php 
    
    // information received from the client
    $recievedInfo = $_POST['foo'];
    
    // do something with this information
    

    See this for your reference http://api.jquery.com/jquery.ajax/

    0 讨论(0)
提交回复
热议问题