get data from mysql database to use in javascript

后端 未结 4 1780
攒了一身酷
攒了一身酷 2020-12-13 05:51

I have a javascript that dynamically builds an html page. In the html page there are textarea boxes for the user to type information in. The information already exists in

相关标签:
4条回答
  • 2020-12-13 06:03

    Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php,

    $result = mysql_query("SELECT field_name, field_value
                           FROM the_table");
    $to_encode = array();
    while($row = mysql_fetch_assoc($result)) {
      $to_encode[] = $row;
    }
    echo json_encode($to_encode);
    

    If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />. You can reference that field with this jQuery: $("#field1").val().

    Here's a complete example with the HTML. If we're assuming your fields are called field1 and field2, then

    <!DOCTYPE html>
    <html>
      <head>
        <title>That's about it</title>
      </head>
      <body>
        <form>
          <input type="text" id="field1" />
          <input type="text" id="field2" />
        </form>
      </body>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
      <script>
        $.getJSON('data.php', function(data) {
          $.each(data, function(fieldName, fieldValue) {
            $("#" + fieldName).val(fieldValue);
          });
        });
      </script>
    </html>
    

    That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value attribute.

    0 讨论(0)
  • 2020-12-13 06:18

    You can't do it with only Javascript. You'll need some server-side code (PHP, in your case) that serves as a proxy between the DB and the client-side code.

    0 讨论(0)
  • 2020-12-13 06:19

    To do with javascript you could do something like this:

    <script type="Text/javascript">
    var text = <?= $text_from_db; ?>
    </script>
    

    Then you can use whatever you want in your javascript to put the text var into the textbox.

    0 讨论(0)
  • 2020-12-13 06:19

    Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?

    1. Send AJAX request to php script
    2. PHP script processes request and builds table
    3. PHP script sends response back to JS in form of encoded HTML
    4. JS takes response and inserts it into the DOM
    0 讨论(0)
提交回复
热议问题