使用带有ajax

时间:2018-06-13 14:55:30

标签: php jquery ajax redirect

我正在创建一个登录脚本(刚开始,我将在稍后查找如何加密密码)。但我无法弄清楚如何重定向到某个页面。

我现在有两种可能性,即管理员或普通用户。

我的剧本:

$conn = new Connection;

$username = $_POST['username'];
$userpassword = $_POST['userpassword'];

if(empty($username) && empty($userpassword)){
  echo 'Vul een gebruikersnaam en wachtwoord in';
}else if(empty($username)){
  echo 'Vul een gebruikersnaam in';
}else if(empty($userpassword)){
  echo 'Vul een wachtwoord in';
}else{
  //Both filled in, begin logincode:
  $getuser = "SELECT * FROM users WHERE username = '".$conn->real_escape_string($username)."'";
  $getusercon = $conn->query($getuser);
  $getuser = $getusercon->fetch_assoc();

  if($userpassword == $getuser['password']){
    if($getuser['rights'] == '1'){
      $_SESSION['user'] = 'admin';
      // header("Location: http://www.mysite.nl/addcompany.php");
      // exit();
      header("Location: http://www.mysite.nl/addcompany.php");
      die();
      echo 'Je bent ingelogd als '.$_SESSION['user'].'';
    }else{
      $_SESSION['user'] = 'user';
      echo 'Je bent ingelogd als '.$_SESSION['user'].'';
    }
  }else{
    echo 'Wachtwoord en gebruikersnaam komen niet overeen';
  }
}

我的ajax代码:

// Login Ajax Code
$( "#content" ).on("submit", "#loginform", function( event ) {
  // Stop normal form behaviour
  event.preventDefault();
  // Haal de inputvelden op met zijn waardes
  var $form = $( this ),
  $username = $form.find( "input[name='username']" ).val(),
  $userpassword = $form.find( "input[name='userpassword']" ).val(),
  url = $form.attr( "action" );
  // Post above values to the action of the form
  var posting = $.post( url, { username: $username, userpassword: $userpassword} );
  // Show result in a div
  posting.done(function( data ) {
    $( "#loginresult" ).empty().slideDown('fast').append( data );
  });
});

我试着用这个:

header("Location: http://www.mysite.nl/addcompany.php");
die();

但我只是看到我的预加载器无限旋转,在我的控制台中我看到以下内容:

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

index.php:1 [DOM] Found 8 elements with non-unique id #example-text-input: (More info: https://www.chromium.org/developers/design-documents/create-amazing-password-forms)

但该ID也在我要重定向的页面上,除非它没有重定向,只是在我的预加载器旋转和这些消息的同一页面上停留。

我该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以在PHP响应中发送重定向标记,并在JS上添加。

例如:

window.location.replace("http://stackoverflow.com");
window.location.href = "http://stackoverflow.com";