我想在 ajax 运行并执行它的操作后插入一个 cookie。 Ajax 大部分时间都在工作。我确实有一个讨厌的错误,我无法解决。但是在那之后运行我希望它插入一个cookie并隐藏一个div。
$('button').click(function() {
var name2 = $('#username').val();
var email2 = $('#email').val();
console.log('starting ajax');
$.ajax({
url: "insert.php",
type: "post",
data: {
email: email2,
username: name2
},
success: function(data) {
var dataParsed = JSON.parse(data);
console.log(dataParsed);
TermsAndConditions();
}
});
});
});
我想运行的附加脚本:
function TermsAndConditions() {
days = 20;
myDate = new Date();
myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = 'TermsAndConditions=Accepted; expires=' + myDate.toGMTString();
}
var cookie = document.cookie.split(';')
.map(function(x) {
return x.trim().split('=');
})
.filter(function(x) {
return x[0] === 'TermsAndConditions';
})
.pop();
if (cookie && cookie[1] === 'Accepted') {
$(".readme").hide();
}
});
这只是一个简单的确认,即用户单击按钮并运行脚本。不过,我似乎无法正常工作。
旁注: 我的 ajax 可以工作,但在 concole 中返回错误。
VM1790:1 Uncaught SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at Object.success (index.php:189)
at c (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at l (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
我的insert.php
$name = $_REQUEST['username'];
$email = $_REQUEST['email'];
$stmt = $pdo->prepare("INSERT INTO index_acknowledge (email, username)
VALUES (?, ?)");
$stmt->execute([$email, $name ]);
$stmt = null;
?>
答案 0 :(得分:0)
好的,所以我的问题是 JSON 返回的错误并且正在停止我的脚本。为了解决这个问题,我在 insert.php 文件中添加了一个返回 json。
我的 insert.php 修复
...
$stmt->execute([$email, $name ]);
$stmt = null;
echo json_encode($stmt);
这是我的固定 jquery
$(function() {
function TermsAndConditions() {
days = 20;
myDate = new Date();
myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000));
document.cookie = 'TermsAndConditions=Accepted; expires=' + myDate.toGMTString();
}
var cookie = document.cookie.split(';')
.map(function(x) {
return x.trim().split('=');
})
.filter(function(x) {
return x[0] === 'TermsAndConditions';
})
.pop();
if (cookie && cookie[1] === 'Accepted') {
$(".readme").hide();
}
$('#acknowledge').on('click', function() {
TermsAndConditions();
return false;
});
$('button').click(function() {
var name2 = $('#username').val();
var email2 = $('#email').val();
console.log('starting ajax');
$.ajax({
url: "insert.php",
type: "post",
data: {
email: email2,
username: name2
},
success: function(data) {
var dataParsed = JSON.parse(data);
console.log(dataParsed);
TermsAndConditions();
$(".readme").hide();
}
});
});
});