通过AJAX从PHP返回值到JS

时间:2016-11-02 10:38:01

标签: javascript php jquery ajax

我做错了什么? AJAX的成功似乎根本没有收到任何东西,因为没有显示三个警报。该过程有效,但我没有得到任何回复

<?php
  require_once('./stripe/config.php');

  $token  = $_POST['tokenid'];
  $email = $_POST['email'];
  $amount = $_POST['amount'] ;
  $description = $_POST['description'] ;

  $err = 'OK' ;

  $customer = \Stripe\Customer::create(array(
      'email' => $email,
      'source'  => $token
  ));

  try { 
    $charge = \Stripe\Charge::create(array(
      'customer' => $customer->id,
      'amount'   => $amount,
      'currency' => 'GBP',
      'description' => $description
    ));
  } catch(\Stripe\Error\Card $e) {
    $err = "Declined - $e";
  }

  function response() {
    global $err;
    print $err ;
    return $err;
  }
  exit response() ;
?>
for($i = 2 ; $i < 100; $i+=5){
    if(($i - 2) % 5 == 0){
        echo 'This is: '. $i.'<br/>';
    }
}

请帮助,因为这让我很生气。

2 个答案:

答案 0 :(得分:0)

删除响应功能,打印错误

 <?php
  require_once('./stripe/config.php');

  $token  = $_POST['tokenid'];
  $email = $_POST['email'];
  $amount = $_POST['amount'] ;
  $description = $_POST['description'] ;

  $err = 'OK' ;

  $customer = \Stripe\Customer::create(array(
      'email' => $email,
      'source'  => $token
  ));

 try { $charge = \Stripe\Charge::create(array(
      'customer' => $customer->id,
      'amount'   => $amount,
      'currency' => 'GBP',
      'description' => $description
  ));
    } catch(\Stripe\Error\Card $e) {
    $err = "Declined - $e";
    }
echo $err;
?>

将dataType设置为文本dataType: 'text',

答案 1 :(得分:0)

您的jQuery AJAX请求被设置为接收JSON(通过dataType属性),但您返回一个字符串。该字符串也重复了几次,response()函数非常冗余。

要解决此问题,请修改您的PHP代码以实际返回JSON,并使用您的jQuery代码正确读取该JSON。试试这个:

$success = true;
$err = '';

$customer = \Stripe\Customer::create(array(
  'email' => $email,
  'source'  => $token
));

try {
  $charge = \Stripe\Charge::create(array(
    'customer' => $customer->id,
    'amount'   => $amount,
    'currency' => 'GBP',
    'description' => $description
  ));
} catch(\Stripe\Error\Card $e) {
  $success = false;
  $err = "Declined - $e";
}

echo json_encode(array('success' => $success, 'err' => $err));
jQuery.ajax({
  type: 'POST',
  url: 'https://xxxxxxxxxxx.com/charge.php',
  data: {
    tokenid: token.id,
    email: customer_email,
    amount: amount,
    description: customer_first_name + ' ' + customer_surname + ' | ' + reference
  },
  dataType: 'json',
  success: function(response) {
    if (response.success) {
      alert('Payment successfully made! ');
    } else {
      console.log(response.err);
      alert('Payment could not be processed. Please try again.');
      location.reload();
    }
  }
});