duanboniao5903 2015-11-04 20:23
浏览 74
已采纳

将数组从一个php页面传递到另一个javascript页面的最佳实践?

I'm using AJAX to send a request to another php page where it returns the result of a query. I was calling it through xmlhttprequest to javascript to get the contents of that php page, but since i was mixing presentation logic "e.g. echo blah blah" with actual code logic I wanted to find a way where I could leave the php logic with my query alone, store the result on an array, and through ajax pass it down to my js code to use in a function.

I'm trying to populate a drop down list with the contents of this array. I've tried json encode but I'm not having any luck.

Here's code for the php page requested:

<html>
<head>
</head>
<body>
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);


$con = mysqli_connect('*******','********','******','****');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

$j = mysqli_real_escape_string($con, $_GET['j']);

mysqli_select_db($con,"4h");
$sql="SELECT nombreClub FROM club4h WHERE oficinaLoc LIKE '%".$j."%'";
$result = mysqli_query($con,$sql);

while($row = $result->fetch_array()) {
    $response[] = $row;
}

file_put_contents('getnombre.php',json_encode($response));

mysqli_close($con);
?>
</body>
</html>

Here's my js function:

function loadDoc(url, cfunc, sel){
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function(){
        if (xhttp.readyState == 4 && xhttp.status == 200){
            cfunc(xhttp);
        }
    }
    xhttp.open("GET", url +sel, true);
    xhttp.send();
}

function selClub(xhttp) {
    document.getElementById("nombreClub").style.display = "inline";
    var optData = <?php file_get_contents('getnombre.php'); ?>;
    var newClub = document.getElementById("addClub");
    newClub.type = "text";
    document.getElementById("addOption").style.display = "inline";
            $("#addOption").click(function(){
            $("#nombreClub").append('<option value="' + $("#addClub").val() + '">' + $("#addClub").val() + '</option>');
            $("#nombreClub").last().focus;
            });
}

I call it through an onchange event when an user clicks a previous drop down list so this drop down list gets populated with options specific for the previous list. I know how to add the options to the list, I'm just having trouble getting the data from the php page to js without having to do something like this:

$a = mysqli_real_escape_string($con, $_GET['a']);

mysqli_select_db($con,"4h");
$sql="SELECT nombre FROM personal4h WHERE unidadProg LIKE '%".$a."%'";
$result = mysqli_query($con,$sql);

echo '<select name="agenteExt" id="agenteExt">
    <option value="">Seleccione Agente</option>';
while($row = mysqli_fetch_array($result)) {
    echo "<option value =" . $row['nombre'] . ">" . htmlentities($row['nombre']) . "</option>";
}

echo "</select>";
mysqli_close($con);
?>
  • 写回答

1条回答 默认 最新

  • dongse5408 2015-11-05 15:55
    关注

    I'll attempt to explain how to do this...

    PHP Query Page

    Query your data and return it as JSON. PHP has a json_encode() function to do this.

    // ...your code to query database which should make an array like this
    $query_results = array(
        array('agent'=>'Agent 1'),
        array('agent'=>'Agent 2'),
        array('agent'=>'Agent 3')
    );
    
    return json_encode($query_results);
    

    HTML Page should have your select

    <select name="agenteExt" id="agenteExt"></select>
    

    JavaScript

    A function to get data via AJAX

    function loadDoc(url, callback){
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function(){
            if (xhttp.readyState == 4 && xhttp.status == 200){
                if( callback ) callback(xhttp)
            }
        }
        xhttp.open("GET", url, true);
        xhttp.send();
    }
    

    The function to get the data to fill your html

    function fillOptions(){
        loadDoc('your-query-page.php', function(xhttp){
    
            // parse the JSON data into a JavaScript object
            var data = JSON.parse(xhttp.responseText);
    
            // get the `<select>` element
            var el = document.getElementById('agenteExt');
    
            var html = '<option>Make a selection</option>';
    
            // loop through data and create each `<option>` for the select
            for(i = 0; i < data.length; i++){
                html += '<option value="'+data[i].agent+'">'+data[i].agent+'</option>'
            }
    
            // update the select with the new options
            el.innerHTML = html;
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)