简体   繁体   English

最佳做法是将数组从一个PHP页面传递到另一个JavaScript页面?

[英]Best practice to pass an array from one php page to a different javascript page?

I'm using AJAX to send a request to another php page where it returns the result of a query. 我正在使用AJAX将请求发送到另一个php页面,在该页面中它返回查询结果。 I was calling it through xmlhttprequest to javascript to get the contents of that php page, but since i was mixing presentation logic "eg 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. 我通过xmlhttprequest调用它来获取Javascript页面的内容,但是由于我将表示逻辑“例如echo blah blah”与实际的代码逻辑混合在一起,因此我想找到一种方法,在查询中保留php逻辑单独将结果存储在数组中,然后通过ajax将其传递给我的js代码以在函数中使用。

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. 我已经尝试过json编码,但是没有运气。

Here's code for the php page requested: 这是请求的php页面的代码:

<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: 这是我的js函数:

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. 我通过用户单击上一个下拉列表时的onchange事件来调用它,因此该下拉列表将填充有特定于上一个列表的选项。 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: 我知道如何将选项添加到列表中,只是在将数据从php页面获取到js时遇到麻烦,而无需执行以下操作:

$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);
?>

I'll attempt to explain how to do this... 我将尝试说明如何执行此操作...

PHP Query Page PHP查询页面

Query your data and return it as JSON. 查询您的数据并将其作为JSON返回。 PHP has a json_encode() function to do this. PHP具有json_encode()函数来执行此操作。

// ...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 HTML页面应由您选择

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

JavaScript 的JavaScript

A function to get data via AJAX 通过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 获取数据以填充您的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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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