我有一个带有一些JS的HTML网页。 JS假设将用户名和密码数据发送到我的服务器,但数据(JSON格式)显示为未定义。由于某种原因,var用户名和密码是“未定义的”,但整个POST以JSON格式显示(这就是我想要的)。
JS:
$(document).ready(function(){
var messageType = "3";
var cookie_name = "username";
var cookie_name2 = "password";
var YouWrote = getName(cookie_name);
var YouWrote2 = getName2(cookie_name2);
var userName = YouWrote;
var password = YouWrote2;
auth(messageType, userName, password);
});
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
function auth(messageType, userName, password) {
$.ajax
({
type: "POST",
//SEND TO SERVER URL
url: "######",
dataType: 'json',
async: false,
data: '{"messageType": "' + messageType + '", "userName": "' + userName + '", "password" : "' + password + '"}',
error: function (xhr, error) {
alert('Error!');
},
success: function (data, textStatus, jqXHR) {
$('#response').html(data.details + '\nHello ' + data.clientInfo.firstName + ' ' + data.clientInfo.lastName + '. \nBalance:' + data.clientInfo.balance);
}
})
}
function getName(cookie_name) {
if(document.cookie)
{
index = document.cookie.indexOf(cookie_name);
if (index != -1)
{
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {nameend = document.cookie.length;}
YouWrote = document.cookie.substring(namestart, nameend);
return YouWrote;
}}}
function getName2(cookie_name2) {
if(document.cookie)
{
index = document.cookie.indexOf(cookie_name2);
if (index != -1)
{
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {nameend = document.cookie.length;}
YouWrote2 = document.cookie.substring(namestart, nameend);
return YouWrote2;
}}}
正确保存Cookie值。它们中有一些东西。在:
data: '{"messageType": "' + messageType + '", "userName": "' + userName + '", "password" : "' + password + '"}',
messageType显示为“3”,但userName和password为“undefined”。这是不是定义全局变量的情况吗?
非常感谢任何帮助。