gpt4 book ai didi

javascript - 想要使用Javascript(ajax)和PHP执行数据库操作而无需重新加载页面

转载 作者:行者123 更新时间:2023-12-03 07:09:51 26 4
gpt4 key购买 nike

我正在尝试编写一段代码来获取输入(电子邮件)表单并保存到数据库

我使用ajax将数据保存到xml文件而不是保存到数据库..并且效果很好。但使用 xml 代替数据库并不安全。用户可以查看整个 xml 和其中的数据。!

所以我想从表单中获取数据并显示电子邮件是否已在数据库中可用。!!我希望所有这一切都像 AJAX 一样在后台发生..我不希望用户被重定向到其他页面或要重新加载的页面。 。我编写了一个 PHP 脚本来检查电子邮件是否已在数据库中。

PHP

<?php

$count=0;
$email = $_POST['subs_input'];
$con1= new PDO('mysql:host=localhost; dbname=emails' , 'root' , '');
$q = "INSERT INTO `emails`.`email` VALUES ('$email')";
$q1 = "SELECT * FROM `emails`.email`";
$result = $con1->query($q1);
while($ret = $result->fetch(PDO::FETCH_ASSOC)){
$ele = $ret['email'];
if($ele == $email){
echo "Email already exists";
$count=1;
}
}
if($count==0){
$con1->query($q);
echo"subscribed sucessfully";
}
?>

我可以将它们包装在 xml 内容中并将 responseXML 发送到 javascript ajax,而不是回显语句。我只需要知道

    if(xmlhttp.readyState == 4 || xmlhttp.readyState == 0){
xmlhttp.open("POST","../text/info.php",true);
...
...
}

如何通过ajax请求将电子邮件(从html输入)发送到php。为了在 php 中访问它..我知道使用 jquery 可以很容易地完成此操作..但我不想使用 JQUERY。我想通过艰苦的方式来学习它。

比你提前;

最佳答案

我想你需要这样的东西。

var dir = "../text/info.php";
var request = new XMLHttpRequest();

var email = document.getElementById("email").value;
var data = "subs_input="+email;

request.open("POST", dir, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", data.length);
request.setRequestHeader("Connection", "close");

request.onload = function() {
if (request.status === 200) {
// code if everything went fine
// request.responseText for printing echoes
} else {
// code if otherwise
}
};

// sending data here
request.send(data);

关于javascript - 想要使用Javascript(ajax)和PHP执行数据库操作而无需重新加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36654853/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com