簡體   English   中英

在查詢中使用document.getElementById或其他方式

[英]Use a document.getElementById into a query or another way to do this

我需要將從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>

有什么建議嗎? 謝謝

這是在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);

send-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變量之前對其進行驗證和轉義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM