我正在尝试构建一个api,用户必须登录才能发布评论。 我已经隐藏了评论按钮并将其设置为在用户登录后显示。
var loggeduser;
function Login(){
$.ajax({
url: 'http://creative.coventry.ac.uk/~4089797/Games/V2.0/Client4/index.php/users/account/'+$("#loginusername").val(),
headers: {Authorization:window.btoa($("#loginusername").val()+':'+$("#loginpassword").val())},
contentType: "get",
dataType: 'json',
success: function(data) {
Authorisation = window.btoa($("#loginusername").val()+':'+$("#loginpassword").val()); //create a variable to pass to the cookie
createCookie('auth',Authorisation,0); //create our authorisation cookie for the client
alert("Details correct. Please continue.");
loggeduser=username;
$("#login").hide(); //hide the login button
$("#create").hide(); //hide the create an account buttons
$("#logout").show(); //show the logout button
$("#addreview").show(); //show the add a review button
$("#adminpanel").show();//show the admin panel page
$("#loginusername").val(''); //clear the name box
$.mobile.changePage("#home"); //show the menu
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
console.log(r);
alert("Error:" + r.error.text);
}
});
}
我已经使用上面的ajax调用来记录用户,并试图将此用户名中的用户名传递给loggeduser。
function Postreview(){ //Add a review to the site
$.ajax({
type:'post',
url: 'http://creative.coventry.ac.uk/~4089797/Games/V2.0/Client4/index.php/games/review/',
data: {ean:reviewean,
review_title:$("#ReviewTitle").val(),
review:$("#Review").val(),
rating:$("#rating").val(),
username:loggeduser},
dataType: 'json',
success: function(data) {
alert("Review Added. Please continue.");
$("#reviewtitle").val(''); //clear the text boxes
$("#review").val('');
$("#rating").val('');
Getreviews(ean);
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
console.log(r);
alert("Error:" + r.error.text);
}
});
}
这是用户发布评论的位置,但是当用户提交评论时,用户名字段为空,因此尚未传递
答案 0 :(得分:0)
在您的登录ajax回复中,loggeduser
设置为username
loggeduser=username;
...但username
似乎不存在?也许你的意思是data.username
?
无论如何,您应该从服务器返回已经过身份验证的用户名,并使用data.username
设置loggeduser
。
此外,将密码存储在cookie中是一个糟糕的主意。你在使用PHP会话吗?
答案 1 :(得分:-1)
这不是AJAX
在A代表asynchronous
你有两个选择
1)在你的Login()
AJAX成功后做了Postreview(用户名)
2)不推荐:async:false用于登录ajax