dougaoshang0237 2018-04-05 13:49
浏览 82
已采纳

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

In log.js the following function is not working for some reason and I really want it to work and maybe someone knows how to use post instead of get so that I don't have to use cookie to retrieve login info in PHP file

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);
    };
  }
}

but without request when I replace that function with this one everything works fine but it opens up a new tab

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

Here is my 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>

here is my 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);
        };
      }
    }

here is mine 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");
}
?>

</div>

展开全部

  • 写回答

1条回答 默认 最新

  • dongzhang8475 2018-04-05 14:48
    关注

    Okay, so instead of using cookies to transfer data with your xmlHttpRequest() you can pass information using the send() function.

    Web APIs | MDN:

    send() accepts an optional parameter which lets you specify the request's body; this is primarily used for request such as PUT. If the request method is GET or HEAD, the body parameter is ignored and request body is set to null.


    Objects

    send() allows for parameters; in this case you can pass the username and password inside of an object:

    .send({
      user: email,
      pass: password
    });
    

    Then in PHP just get the $_POST data into the correct array:

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

    Serialize

    Or you can serialize the data into a string:

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

    Then send it:

    .send(params);
    

    If you are using jQuery you can also use their handy little serialize() function.

    $('form').serialize();
    

    Which will simply put the items into a string as shown above.

    Once you receive the data in the login.php file you can parse the string if serialized, and if you put them into the object, you can just use your standard $_POST variable.

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

    Resolution

    Your login() function:

    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
            });
        }
    }
    

    Then your refreshData() function would look like this:

    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);
            };
        }
    }
    

    Promises

    Or, better yet, you can use fetch() which is a better (newer) alternative to xmlHttpRequest. You can also use promises - which work very well.

    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);
        });
    }
    

    That is the new method of implementing AJAX call, if you are interested look MDN's documentation, they are very good and there are also good examples.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部