我有以下 jQuery:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
event.preventDefault();
var email = $('.email').val();
$.ajax({
type: "POST",
url: "register_email.php",
data: JSON.stringify({ "email": email }),
dataType: "json",
contentType: "application/json",
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
});
});
email
变量肯定已设置,我可以提醒
它。
但是,当我使用 PHP 时,这是我的脚本:
<?php
$db = new mysqli("localhost", "...", "...", "...");
if ($db->connect_error) {
echo "Could not connect to database.";
exit;
}
else {
$emerd = json_decode($_POST["email"]);
$db->query("INSERT INTO emails (email) VALUES (' " . $emerd . "')");
echo $emerd;
}
?>
它总是向我提示“null”。为什么它不理解我发布的内容?
最佳答案
将您的电子邮件字段放在这样的表单中
<form id="myform"><input type="text" name="email"></form>
然后用jQuery序列化
$('#myform").on('submit', function (e) {
e.preventDefault();//this keeps the form submission from refreshing the page
var data = $(this).serialize();
$.ajax({
url: '',
data: data, //assign the data like this
type: "post",
success: function (response){
},
....other params
})
})
这是执行此操作的最佳方法恕我直言,我认为这是针对此类事情的推荐方法。无需编码为 JSON,然后在服务器端解码 JSON。
关于javascript - 为什么当我在 AJAX 中使用 POST 将数据发送到 PHP 时,它说变量为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18280119/