Vuejs ajax呼叫无法正常工作

时间:2018-04-18 16:29:00

标签: php ajax vue.js session-variables

嘿所有人所以我正在尝试制作一个对php页面进行ajax调用的vueapp。在那个php页面上,我运行了一些mysql语句,其中最重要的是insert语句。如果该页面ajax调用成功并且insert语句成功运行,我想重定向页面。如果ajax调用或insert语句失败或用户存在,我想将它们重定向到同一页面,只是根据结果不同地呈现页面。我尝试过使用会话,但是当我尝试使用ajax错误函数时,即使成功也会每次都触发它。我知道这是因为我收到警报错误。但是当它进入result.php页面时,我获得了成功。我不明白任何帮助都会很棒!

<?php ob_start();
session_start();
include('head.php');
include('header.php');
?>
<div id="signUpFormContainer">
  <div id="signUpForm">
    <div class="inputDiv">
      <p>Username*</p>
      <input v-model="userName" placeholder="joseChang">
    </div>
    <div class="inputDiv">
      <p>Password*</p>
      <input type="password" v-model="password" placeholder="********">
    </div>
    <div class="inputDiv">
      <p>Confirm Password*</p>
      <input type="password" v-model="confirmPassword" placeholder="********">
    </div>
    <div class="inputDiv">
      <p>First Name*</p>
      <input v-model="firstName" placeholder="Jose">
    </div>
    <div class="inputDiv">
      <p>Last Name*</p>
      <input v-model="lastName" placeholder="Chang">
    </div>
    <div class="inputDiv">
      <p>Email*</p>
      <input v-model="email" placeholder="jchang@example.com">
    </div>
    <div class="inputButton">
      <input v-on:click.prevent="makeAccount" id="addButton" type="button" value="Sign Up"></input>
    </div>
  </div>
</div>
<div id="footerContainer"></div>

<script>
var app = new Vue({
  el: '#signUpForm',
  data: {
    userName: '',
    password: '',
    confirmPassword: '',
    firstName: '',
    lastName: '',
    email: ''
  },
  computed: {
    passwordsMatch: function() {
      if(this.password == this.confirmPassword) {
        return true;
      } else {
        return false;
      }
    },
    passwordRequirementsMet: function() {
      if(this.password.length >= 8) {
        return true;
      } else {
        return false;
      }
    },
    validEmail: function() {
      var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
      if (!reg.test(this.email)) {
        return false;
      }
      return true;
    }
  },
  created: function() {
  },
  watch: {
  },
  methods: {
    makeAccount: function() {
      if(this.userName.length >= 8 && this.firstName != '' && this.lastName != '' && this.validEmail && this.passwordRequirementsMet && this.passwordsMatch) {
        var jsonString = JSON.stringify({
          userName: this.userName,
          firstName: this.firstName,
          lastName: this.lastName,
          password: this.password,
          email: this.email
        });
        $.ajax({
          url: 'makeAccount.php',
          dataType: 'json',
          type: 'post',
          contentType: 'application/json',
          dataType: 'json',
          data: jsonString,
          error: function(){
          alert('Error');
           window.location.href='result.php';
          },
          success: function(data){
            console.log(data);
            alert('success');
           window.location.href='result.php';
          }.bind(this)
        });
     }
    }
    }
  });

</script>
<?php include('foot.php');?>

?>

继承了php页面的代码,我发出ajax请求。 (makeAccount.php)

<?php session_start();
$_SESSION['hitpage']=1
require_once('database.php');
  require_once('functions.php');  
  $requestBody = file_get_contents('php://input');
  $requestJSON = json_decode($requestBody);

  require_once 'lib/Braintree.php';

  $gateway = new Braintree_Gateway([
    'environment' => 'sandbox',
    'merchantId' => 'ygpmj36rrztwbw6x',
    'publicKey' => 'qrf7ncz6kskchgfh',
    'privateKey' => '2e9ab466fca6889dd5e570ac583c8a46'
  ]);

  $braintreeResponse = $gateway->customer()->create([
    'firstName' => $requestJSON->firstName,
    'lastName' => $requestJSON->lastName,
    'email' => $requestJSON->email
  ]);
  if ($braintreeResponse->success) {
    echo(json_encode($braintreeResponse));
  } else {
    echo(json_encode($braintreeResponse));
  }

  function get_data($url) {
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
  }

  $googleResponse = get_data('https://script.google.com/macros/s/AKfycbzz8Oh3Jqt5tP4wGcNyM8jVhwaMEr6S5AJ-MWqFlhPN1rSzBdSr/exec?name='.urlencode(stripslashes($requestJSON->userName)));

  function get_string_between($string, $start, $end){
      $string = ' ' . $string;
      $ini = strpos($string, $start);
      if ($ini == 0) return '';
      $ini += strlen($start);
      $len = strpos($string, $end, $ini) - $ini;
      return substr($string, $ini, $len);
  }

  $googleResponseParsed = get_string_between($googleResponse, '<title>', '</title>');

  echo($googleResponseParsed);
$username = $requestJSON->userName;
$username = mysqli_real_escape_string($mysqli, $username);
$firstname = $requestJSON->firstName;
$firstname = mysqli_real_escape_string($mysqli, $firstname);
$lastname = $requestJSON->lastName;
$lastname = mysqli_real_escape_string($mysqli, $lastname);
$email = $requestJSON->email;
$email = mysqli_real_escape_string($mysqli, $email);
$cleanGoogleResponseParsed = $googleResponseParsed;
$cleanGoogleResponseParsed = mysqli_real_escape_string($mysqli, $cleanGoogleResponseParsed);
$customerid = $braintreeResponse->customer->id;
$customerid = mysqli_real_escape_string($mysqli, $customerid);

$password = $requestJSON->password;
$encryptedpassword=password_encrypt($password);
  $makeUserSQL = "INSERT INTO user (userName, firstName, lastName, email, driveFolderId, braintreeId, password)
  VALUES ('".$username."','".$firstname."','".$lastname."','".$email."','".$cleanGoogleResponseParsed."','".$customerid."','".$encryptedpassword."')";

  if ($mysqli->query($makeUserSQL) === TRUE) {
      echo "New record created successfully";
      $_SESSION['inserted'];
  } else {
      echo "Error: " . $makeUserSQL . "<br>" . $mysqli->error;
  }

$mysqli->close();

?>

继承了result.php的代码

<?php session_start();
if(isset($_SESSION['hitpage'])){$ajaxworked=1;} else{$axjaxworked=0;}
if(isset($_SESSION['inserted'])){$inserted=1;} else {$inserted=0;}
if($inserted==1 and $ajaxworked==1){echo 'success';}
if($inserted==0 and $ajaxworked==0){echo 'failed';}
session_destroy();
?>

2 个答案:

答案 0 :(得分:1)

this.userName不存在。

您也可以直接执行此操作,而不是传递变量:

 window.location.href="successfullycreated.php?userName="+ <?php echo "'{$_GET['userName']}'";?>;

答案 1 :(得分:1)

只要新页面中存在param,您就可以从JavaScript中的URL中获取它。

var userName = new URL(window.location.href).searchParams.get("userName");