get data from mysql database to use in javascript

后端 未结 4 1793
攒了一身酷
攒了一身酷 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: . 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

    
    
      
        That's about it
      
      
        

    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.

提交回复
热议问题