简体   繁体   中英

Dynamic select list (JavaScript)

Does anyone know how I could get the select options in the following to be populated from a SQL DB?:

        var cell2 = row.insertCell(1);
        var sel = document.createElement('select');
        sel.name = 'selRow' + rowCount;
        sel.options[0] = new Option('text zero', 'value0');
        sel.options[1] = new Option('text one', 'value1');
        cell2.appendChild(sel); 

Thanks, B.

Javascript can't directly connect to a database, you're going to need some server-side (PHP, ASP, Coldfusion, etc.) code to do that.

UPDATE: 1. In PHP create a page that reads the database & outputs XML or JSON or even the HTML code itself 2. In Javascript make an AJAX call to that PHP page 3. Use Javascript parse the XML/JSON/HTML response to update the page.

Using a library like JQuery will make this much easier to code. Let's assume your generating the HTML code in PHP & using JQuery, you could make & parse the AJAX call like this:

$.get("YourPHPPage.php", function(data){
   $('.DynamicSelect').html(data);
});

That will make an ajax call to the PHP page, and insert the result into your select box.

要么在生成页面时采取输出每条sel.options[x]行的漫长而sel.options[x]路线,要么如果您想基于表单上的其他信息来进行输出,则使用AJAX是这样。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM