dssu33392 2013-02-11 08:55
浏览 96
已采纳

用一个按钮调用php和javascript函数

This is what I'm trying to achieve, but my Googling hasn't helped:

I have a button that adds a new row to a table dynamically. I also add a select component to a cell with the same action all in javascript. I'd like for that select component to populate with values from a sql select statement. Of course I don't want to define the connection to the DB in the JavaScript. So I was wondering if there was a way I could call a PHP function to retrieve the values then store it in variable within JavaScript.

PS I understand that PHP is server side as opposed to JS. But surely this is possible.

  • 写回答

5条回答 默认 最新

  • dongxiong1941 2013-02-11 09:08
    关注

    here's a simple implementation of such a thing using jQuery's ajax and php.

    html

    <select data-source-url="/category/list"></select>
    

    javascript using jQuery

    $("select[data-source-url]").each(function(){
        var url = $(this).attr("data-source-url");
        var el = $(this);
        $.get(url, function(data){
            for (i=0;i<data.length;i++){
                el.append("<option>" + data[i] + "</option>");
            }
        },"json");
    });
    

    category/list endpoint (a php script)

    $list = array();
    $list[0] = "category 1";
    $list[1] = "category 2";
    $list[2] = "category 3";
    $list[3] = "category 4";
    $list[4] = "category 5";
    
    echo json_encode($list);
    

    a little explanation: what happens is a request being made via the JavaScript client to a php script, which returns an array of values in JSON (which is basically a javascript data-structure), those values are added to the select box dynamically.

    Please note that on initial load of the page, the select box will be empty.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频