[英]Insert mysql data using javascript and ajax
基本上,我需要異步插入textarea的值,但是當我調用函數insertSQLData()時,它會顯示頁面的源代碼,除此之外,我找不到其他錯誤。 我省略了數據庫代碼以及任何不相關的代碼。
<?php
$q = $_GET["q"];
$username = $_COOKIE["user"];
?>
function insertSQLData(str){
if(str == 0){
document.getElementById("holder").innerHTML="";
return;
}
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("holder").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index-async.php?q=+str", true);
xmlhttp.send();
}
<form action="" method="get">
<textarea onblur="insertSQLData(this.value);" id="quick-post-form" name="quick-post-form"></textarea>
<input type="button" value="Submit" name="quick-post-btn" id="quick-post-submit">
<div id="holder"></div>
if(isset($username) && !empty($q)){
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', '$username')");
} elseif(!empty($q)) {
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', 'Guest User')");
}
您必須先加載它,然后才能啟動php文件。
您要做的就是編寫一個控制器,並在任何地方(而不是index.php)使用它(在從DB加載這些東西之后),將用戶重定向到提供所需數據的index.php頁面。
因此,您正在調用ajax調用所在的同一頁面。顯然,它返回了代碼。
在另一個文件中編寫php代碼,然后嘗試調用它。 有用
您可以按照以下條件在條件語句中編寫代碼。
<?php
if(isset($_GET["q"]))
{
$q = $_GET["q"];
$username = $_COOKIE["user"];
if(isset($username) && !empty($q)){
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', '$username')");
} elseif(!empty($q)) {
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', 'Guest User')");
}
}
else
{
?>
<script>
function insertSQLData(str){
if(str == 0){
document.getElementById("holder").innerHTML="";
return;
}
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("holder").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index-async.php?q=+str", true);
xmlhttp.send();
}
</script>
<form action="" method="get">
<textarea onblur="insertSQLData(this.value);" id="quick-post-form" name="quick-post-form"></textarea>
<input type="button" value="Submit" name="quick-post-btn" id="quick-post-submit">
<div id="holder"></div>
<?php
}
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.