[英]Use a document.getElementById into a query or another way to do this
I need to insert a value got from a document.getElementById into a sql query. 我需要将从document.getElementById获得的值插入到SQL查询中。 I need to do this because i'm trying to autofill a second input box depending on the result of the first (ie if i type Rome in the first one i would like the second one to autofill with the related country found in my db, like Italy)
我需要这样做是因为我要根据第一个输入框的结果自动填充第二个输入框(即,如果我在第一个输入框中键入Rome,我希望第二个输入框自动填充数据库中的相关国家/地区,像意大利)
Here is the code: 这是代码:
<?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>
Any suggestion? 有什么建议吗? Thanks
谢谢
Here is a slightly modified version of an AJAX example script found on Wikipedia. 这是在Wikipedia上找到的AJAX示例脚本的略微修改版本。 It should give you the basic idea on how to proceed.
它应该为您提供有关如何进行的基本想法。 If you use jQuery then a lot of this JavaScript could be reduced to just a few lines.
如果您使用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: 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;
By the way, the $city variable should be validated and escaped prior to using it in an SQL query. 顺便说一句,应该在SQL查询中使用$ city变量之前对其进行验证和转义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.