【问题标题】:Use a document.getElementById into a query or another way to do this在查询中使用 document.getElementById 或其他方式来执行此操作
【发布时间】:2016-06-29 22:06:28
【问题描述】:

我需要将从 document.getElementById 获取的值插入到 sql 查询中。 我需要这样做,因为我正在尝试根据第一个输入框的结果自动填充第二个输入框(即,如果我在第一个输入框中键入 Rome,我希望第二个输入框自动填充在我的数据库中找到的相关国家,像意大利)

代码如下:

 <?php
    echo (" <form NAME='Form1' id='Form1' method=post  class=statsform action=page.php  >  " );
    echo ("  <input type=text  name=city   id=city  size=50 class=formfield value='$city'  onBlur='Assigncode();'   >   " );
    echo (" <input type=text name='Country' id='Country' size=12  value='$Country'  >  " );
?>
<script>
function Assigncode() {
    var elemento    = document.getElementById("city");      
    var elementoCod = document.getElementById("Country");       
    if (elemento != null && elemento.value != '') {
        var city = elemento.value;
        if (elementoCod == null || elementoCod.value == '') {
            <?php
$query2 = "SELECT *  FROM table WHERE city = 'put here the getElementById of the city'  ";
$result2 = MYSQL_QUERY($query2);
$i2 = 0;
    $country        =   mysql_result($result2,0,"T_Country");
    ?>

            eval( "document.Form1. Country").value = '<?php echo($country)?>';
        }
    }
}  
</script>

有什么建议吗? 谢谢

【问题讨论】:

  • 你需要使用 AJAX 来做你想做的事。你有使用 AJAX 的经验吗?
  • PHP 早在 javascript 在浏览器中运行之前就在服务器上运行。你不能像这样混合它们
  • 不可能。 PHP在服务器端运行,JS在客户端运行。您可能想使用 ajax 调用
  • 不幸的是,Ajax 的经验为零!
  • 提交表单,然后从提交的数据中获取您需要的内容。

标签: javascript autofill


【解决方案1】:

这里是在 Wikipedia 上找到的 AJAX 示例脚本的略微修改版本。它应该为您提供有关如何进行的基本想法。如果你使用 jQuery,那么这些 JavaScript 的大部分内容可以减少到几行。

// This is the client-side javascript script. You will need a second PHP script
// which just returns the value you want. 

// Initialize the Http request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php?city=' + elemento.value);

// Track the state changes of the request.
xhr.onreadystatechange = function () {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    if (xhr.readyState === DONE) {
        if (xhr.status === OK) {
            document.Form1.Country.value = xhr.responseText; // 'This is the returned text.'
        } else {
            alert('Error: ' + xhr.status); // An error occurred during the request.
        }
    }
};

// Send the request to send-ajax-data.php
xhr.send(null);

发送-ajax-data.php:

<?php
$city = $_GET['city'];
$query2 = "SELECT *  FROM table WHERE city = '$city'";
$result2 = MYSQL_QUERY($query2);
$country =   mysql_result($result2,0,"T_Country");
echo $country;

顺便说一句,在 SQL 查询中使用 $city 变量之前,应该对其进行验证和转义。

【讨论】:

  • 为什么投反对票?这不是实现目标的方法吗?
猜你喜欢
  • 1970-01-01
  • 2015-08-05
  • 2013-02-22
  • 1970-01-01
  • 2013-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多