简体   繁体   English

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

[英]XML HTTP request fails to send request to my PHP file from JS

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

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 : 这是我的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 这是我的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 这是我的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"); } ?> 

Okay, so instead of using cookies to transfer data with your xmlHttpRequest() you can pass information using the send() function. 好的,因此可以使用send()函数传递信息,而不是使用cookies通过xmlHttpRequest()传输数据。

Web APIs | Web API | MDN: MDN:

send() accepts an optional parameter which lets you specify the request's body; send()接受一个可选参数,该参数使您可以指定请求的正文; this is primarily used for request such as PUT. 这主要用于请求(例如PUT)。 If the request method is GET or HEAD, the body parameter is ignored and request body is set to null. 如果请求方法是GET或HEAD,则将忽略body参数,并将请求正文设置为null。


Objects 对象

send() allows for parameters; send()允许参数; in this case you can pass the username and password inside of an object : 在这种情况下,您可以在object内部传递用户名和密码:

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

Then in PHP just get the $_POST data into the correct array: 然后在PHP中,只需将$_POST数据放入正确的数组中即可:

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. 如果您使用的是jQuery,则还可以使用其方便的little serialize()函数。

$('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. 一旦在login.php文件中接收到数据,就可以对字符串进行序列化分析,如果将其放入对象中,则可以使用标准的$_POST变量。

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

Resolution 解析度

Your login() function: 您的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
        });
    }
}

Then your refreshData() function would look like this: 然后,您的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);
        };
    }
}

Promises 承诺

Or, better yet, you can use fetch() which is a better (newer) alternative to xmlHttpRequest . 或者,更好的是,您可以使用fetch() ,它是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. 那是实现AJAX调用的新方法,如果您有兴趣查看MDN的文档 ,它们非常好,并且也有很好的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM