从AJAX / PHP获取JavaScript的多个LIVE值

时间:2014-12-09 18:00:04

标签: javascript php html sqlsrv

我正在创建一个Web应用程序,我正在尝试这样做,当您输入提供程序的ID时,它会自动将它们输出到span中,这是我的AJAX / JS调用

<script>
    function showHint(str) 
    {
        if (str.length == 0)
        { 
            document.getElementById("txtHint").innerHTML = "";
            return;
        }
        else
        {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function()
            {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                {
                    document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
                }
            }
        xmlhttp.open("GET", "../include/proveedores.php?q=" + str, true);
        xmlhttp.send();
        console.log(telfValor);
        }
    }
    </script>
<span id="txtHint"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">

这是它调用来进行搜索的.php

<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = $_REQUEST["q"];

$descrip = "";

// lookup all hints from array if $q is different from "" 
if ($q !== "")
{
    $sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
    $stmt = sqlsrv_query($conex, $sql);
    $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
    $descrip = $row['Descrip'];
    $telf = $row['Telef'];
}

// Output "no suggestion" if no hint was found or output correct values 
echo $descrip === "" ? "no suggestion" : $descrip;
?>

有没有办法实现这个目标?

编辑:这是为了进行AJAX调用,只需1次AJAX调用就可以将各种值返回到跨度

<script src="../js/jquery.js" type="text/javascript"></script>
    <script>
    function showHint(str)
    {
// If there is nothing on the textbox, there is nothing in the spans
        if (str.length === 0)
        {
            $('#Span Name').html("");
            $('#Telephone').html("");
            return;
        }

        $.ajax
        ({
//Here goes the file which contains the SQL call
            url: "../include/proveedores.php",
            data: {'q': str},
            dataType: "json",
            type: "GET",
// Here goes the data that goes into the spans
            success: function (data, status, jqXhr)
            {
                $("#Span Name").html(data["Array Name"]);
                $("#Telephone").html(data["Telephone"]);
            },
            error: function (jqXhr, textStatus, errorThrown)
            {
                console.log("Error response:", jqXhr.responseText);
            }
        });
    }
    </script>
// This is the text input that will be sent to your query file
<input type="text" onkeyup="showHint(this.value)">
<span id="Span Name"></span>
<span id="Telephone"></span>

proveedores.php:

<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL, this is what you have posted
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";

$descrip = "";

if (isset($q) && $q !== "")
{
// THIS IS PRONE TO SQL INJECTION! USE INTERNALLY!
    $sql = "SELECT * FROM PROVIDERS WHERE CodProv LIKE '$q'";
    $stmt = sqlsrv_query($conex, $sql);
    $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
    $Variable = $row['Column Name'];
    $Telf = $row['Telef'];
    $Direc = $row['Direc1'];
}

// This is the array to be encoded to AJAX
$values = array();

// Output "no suggestion" if no hint was found or output correct values 
$values["ArrayName"] = ($Variable === "") ? "no suggestion" : $Variable;
$values["Telephone"] = ($Telf === "") ? "" : $Telf;

// Output the json data
print_r(json_encode($values));
?>

1 个答案:

答案 0 :(得分:1)

首先,你应该使用像jQuery这样的javascript库来处理所有棘手的AJAX提升。它会让你的生活变得更轻松。如果你想使用常规的javascript,你可以返回一个以逗号分隔的字符串,然后解析用逗号分隔的每个值,但这可能会变得混乱。话虽如此,您可以使用jQuery AJAX并在JSON编码的数据对象中返回您的数据。

<强> .PHP

<?
include('conexion.php');
$conex=conex();
// get the q parameter from URL
$q = isset($_REQUEST["q"]) ? $_REQUEST["q"] : "";

$descrip = "";

// lookup all hints from array if $q is different from "" 
if ($q !== "")
{
    $sql = "SELECT * FROM SAPROV WHERE CodProv LIKE '$q'";
    $stmt = sqlsrv_query($conex, $sql);
    $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
    $descrip = $row['Descrip'];
    $telf = $row['Telef'];
}

$values = array();

// Output "no suggestion" if no hint was found or output correct values 
// NOTE: we're using the same "txtHint" here for the key as we do in the javascript function
$values["txtHint"] = ($descrip === "") ? "no suggestion" : $descrip;
// Set these to something useful
$values["txtPhone"] = "";
$values["txtAddress"] = "";

// Output the json data
print_r(json_encode($values));
?>

现在,对于jQuery实现。您要做的第一件事是从jQuery's website下载jQuery库。我建议使用最新版本(目前是jQuery 2.x)。

<强> html的

<script src="/script/jquery.js" type="text/javascript"></script>
<script>
    function showHint(str) {
        if (str.length === 0) {
            $('#txtHint').html(""); 
            return;
        }

        $.ajax({
            url: "../include/proveedores.php",
            data: {'q': str},
            dataType: "json",
            type: "GET",
            success: function (data, status, jqXhr) {
                $("#txtHint").html(data["txtHint"]);
                // You can do this same thing for the other data returned
                $("#txtPhone").html(data["txtPhone"]);
                $("#txtAddress").html(data["txtAddress"]);

            },
            error: function (jqXhr, textStatus, errorThrown) {
                console.log("Error response:", jqXhr.responseText);
            }
        });

        // Not sure where this is defined. It might throw an error
        console.log(telfValor);
    }
</script>
<span id="txtHint"></span>
<span id="txtPhone"></span>
<span id="txtAddress"></span>
<input id="numa" type="text" onkeyup="showHint(this.value)">

显而易见的变化是调用$.ajax()而不是使用XmlHttpRequest()对象。它本身就是不言自明的。有一点我想提一下,因为我们设置&#34;类型&#34; to&#34; GET&#34;,&#34;数据&#34;中的键值对将作为查询字符串附加到网址中:"url?key1=value1&key2=value2&etc..."。因此,在我们的示例中,生成的网址为"../include/proveedores.php?q=[VALUE_OF_STR]",其中[VALUE_OF_STR]是str变量的值。

值得注意的另一个变化是jQuery有一个非常有用的方法来选择元素。如果您想通过ID获取元素,可以使用语法:$('#txtHint')

'#'符号表示我们正在根据ID查找元素,'txtHint'是您要查找的元素的ID。您可以在docs中阅读有关jQuery选择器的更多信息。