XML HTTP请求无法从JS向我的PHP文件发送请求

时间:2018-04-05 21:49:16

标签: php jquery xml cookies xmlhttprequest

log.js中,由于某种原因,以下功能无效,我真的希望它能够正常工作,也许有人知道如何使用post而不是get,这样我就不必使用cookie来检索登录信息在PHP文件中

function refreshData(file,msg){
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("GET", file);
  xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xmlhttp.send();
  xmlhttp.onreadystatechange = function() {
    if (this.readyState === 4 && this.status === 200) {
      location.reload();
    } else {
      swal(msg);
    };
  }
}

但是当我用这个替换该功能时没有请求一切正常,但它打开了一个新标签

function refreshData(file,msg){
  window.open("login.php");
}

这是我的index.php

<DOCTYPE! HTML>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script src="/cafe/script/main2.js"></script>
	<link rel='stylesheet' type='text/css' href='../style/main.css' media='screen' />
</head>
<body>

<div align='left' class='nav-top'>
	<a class='logo' id='logo'>kush.</a>
	<a class='logo2' id='logo'>by</a>
	<a href='../novosti' id='btnNews'>news</a>
	<a href='../zavedenia' id='btnPlaces'>places</a>
	<a href='../kontakty' id='btnContacts'>contacts</a>
	<a href='../blog' id='btnBlog'>blog</a>
<script src='log.js'></script>
</body>
</html>

这是我的log.js

var authentication = "no";
var authentication=getCookie("auth");
var email=getCookie("email");

	if(authentication=="logged_in")
	{
		//some code
		if(email.indexOf("@cafe.eda")>-1)
		{
			loadCafeProfile(email);
		}
		else
		{
			loadPersonProfile(email);
		}
	}
	else
	{
		//some code
		var login = document.getElementById("btnLogIn");
		login.addEventListener('click', logIn);
	}

	function logIn()
	{
		var email = document.getElementById("InputEmail").value;
		var pass = document.getElementById("InputPass").value;
		var re = /^[a-zA-Z0-9]+$/i;
		if(!validateEmail(email))
		{
			swal("check  email");
		}
		else if(pass.length<6)
		{
			swal("max password length 6 char");
		}
		else
		{
			setCookie("email",email,1);
			setCookie("pass",pass,1);
			refreshData("login.php","login in");
		}
	}

function validateEmail(email)
{
    //email validation
    return //true false
}

function setCookie(cname,cvalue,exdays)
{
	var d = new Date();
	d.setTime(d.getTime()+(exdays*24*60*60*1000));
	var expires="expires="+d.toGMTString();
	document.cookie=cname+"="+cvalue+";"+expires+";path=/";
}

function getCookie( name )
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    var end = null;
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0)
        {
        	return null;
        }
        end = document.cookie.indexOf(";", begin);
    } 
    else
    {
        begin += 2;
        end = document.cookie.indexOf(";", begin);
        if (end == -1)
        {
            end = dc.length;
        }
    }
    return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/"/g, '');
}



function loadCafeProfile(email)
	{
		//load cafe profile
	}
	function loadPersonProfile(email)
	{
		//loads persons profile
	}

function refreshData(file,msg){
      var xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET", file);
      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlhttp.send();
      xmlhttp.onreadystatechange = function() {
        if (this.readyState === 4 && this.status === 200) {
          location.reload();
        } else {
          swal(msg);
        };
      }
    }

这是我的login.php

<?php
$ini_array = parse_ini_file("../../db.ini");
$servername=$ini_array['sn'];
$username=$ini_array['un'];
$password=$ini_array['pw'];
$dbname=$ini_array['dn'];
	setcookie("jumbo","jumbo",time()+3600,'/');
	$conn=new mysqli($servername,$username,$password,$dbname);
	
	//check conection
	if(!$conn)
	{
		setcookie('error','connection_fail',time()+3600,'/');
		//header("Location:../cafe");
	}
	$email=mysqli_real_escape_string($conn,$_COOKIE['email']);
	$pass=mysqli_real_escape_string($conn,$_COOKIE['pass']);

	$email = filter_var($email, FILTER_SANITIZE_EMAIL);

// Validate e-mail and password
if (filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match('/[^A-Za-z0-9]/', $pass))
{
	$pass=md5(sha1(md5($pass)));
	if(strpos($email,'@cafe.eda')!==false)
	{
		$sql="SELECT * FROM cafe WHERE email='".$email."' and parol='".$pass."'";
	}
	else
	{
		$sql="SELECT * FROM rebyata WHERE email='".$email."' and parol='".$pass."'";
	}
	$result = mysqli_query($conn, $sql);
	if ($row = mysqli_fetch_array($result, MYSQLI_BOTH))
	{
		setcookie('auth','logged_in',time()+3600*2400,'/');
		setcookie('ses',md5($email.$pass),time()+3600*2400,'/');
		//echo "<script>window.close();</script>";
	}
	else
	{
		setcookie('error','loginfail',time()+3600*2400,'/');
		//header("Location:../cafe");
	}
}
else
{
	setcookie('error','wrong_input',time()+3600*2400,'/');
	//header("Location:../cafe");
}
?>

1 个答案:

答案 0 :(得分:0)

好的,所以您可以使用cookies功能传递信息,而不是使用xmlHttpRequest()send()传输数据。

Web API | MDN:

  

send()接受一个可选参数,允许您指定请求的正文;这主要用于PUT等请求。如果请求方法是GET或HEAD,则忽略body参数并将请求体设置为null。

物件

send()允许参数;在这种情况下,您可以在object

内传递用户名和密码
.send({
  user: email,
  pass: password
});

然后在PHP中将$_POST数据放入正确的数组中:

if($_POST)
{
    $email = $_POST['user'];
    $password = $_POST['pass'];
}

序列化

或者您可以将数据序列化为字符串:

var params = "email="+ email + "&pass="+ password;

然后发送:

.send(params);

如果你正在使用jQuery,你也可以使用他们方便的小serialize()函数。

$('form').serialize();

这将简单地将项目放入如上所示的字符串中。

收到login.php文件中的数据后,您可以解析字符串(如果已序列化),如果将它们放入对象中,则可以使用标准$_POST变量。

if($_POST)
{
    parse_str($_POST, $form);
    // you can now get the post data into an array:
    $form['email'];
    $form['password'];
}

分辨率

您的login()功能:

function logIn() {
    var email = document.getElementById("InputEmail").value;
    var pass = document.getElementById("InputPass").value;
    var re = /^[a-zA-Z0-9]+$/i;
    if (!validateEmail(email)) {
        swal("check  email");
    } else if (pass.length < 6) {
        swal("max password length 6 char");
    } else {
        refreshData("login.php", {
                email: email,
                password: pass
        });
    }
}

然后您的refreshData()函数将如下所示:

function refreshData(file, data) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("POST", file);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);
    xmlhttp.onreadystatechange = function () {
        if (this.readyState === 4 && this.status === 200) {
            location.reload();
        } else {
            swal(msg);
        };
    }
}

承诺

或者,更好的是,您可以使用fetch(),这是xmlHttpRequest的更好(更新)的替代方案。你也可以使用promises - 它可以很好地工作。

function refreshData(url, data) {
    return fetch(url, {
        body: JSON.stringify(data),
        cache: 'no-cache',
        method: 'POST',
        mode: 'cors'
    })
    .then(function(response){
        return response.json();
    })
    .catch(function(e) {
            console.log("Error: ", e);
    });
}

这是实现AJAX调用的新方法,如果你感兴趣的话看MDN's documentation,它们非常好,也有很好的例子。