如何在ajax中精确输出

时间:2016-05-31 23:22:24

标签: php ajax

我的代码运行良好,但输出问题。我没有得到我想要的确切输出。

$("#search_traveller_button").click(function(){
                $.ajax({
                    url: "index.php?act=checkSessionUser",
                    type: "POST",
                    cache: false,
                    success: function(data){
                            console.log(data);
                    },
                    error:function(){
                        console.log("Error: Unknown Error");
                    }
                });
            });

PHP代码:

<?php
if(isset($_SESSION['userId'])) {
    echo "1";
} else {
    echo "0";
}
?>

输出成功还提供了HTML代码,为什么?

0   </div>
        <footer class="nav navbar-inverse">
        ...........
        </footer>
    </body>
</html>

我只想在输出中输出0变量,而不是html代码。

2 个答案:

答案 0 :(得分:1)

问题在于你的php代码这里是一个示例php代码。你需要编码为JSON,这让jQuery .success或.fail有一个JSON响应作为回调。

我正在做的是我有一个php文件和一个js文件。

PHP

<?php
  $name = $_POST['name'];
  $email = $_POST['email'];
  $msg = $_POST['message'];

  $nospace_name = trim($_POST['name']);
  $nospace_email = trim($_POST['email']);
  $nospace_message = trim($_POST['message']);

  if (empty($nospace_name))
    $errors['name'] = "Name field is required.";

  if (empty($nospace_email))
    $errors['email'] = "Email field is required.";

  if (empty($nospace_message))
    $errors['message'] = "I would love to see your message.";

  if (!empty($nospace_email) && !preg_match("^[a-zA-Z0-9_\-\.]+@[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$^", $nospace_email))
    $errors['bad_email'] = "Please enter a valid email address";


  // if there are any errors in our errors array, return a success boolean of false
  if (!empty($errors)) {
    // if there are items in our errors array, return those errors
    $data['success'] = false;
    $data['errors']  = $errors;
  }
  else {
    // if there are no errors process our form, then return a message

    // prepare message to be sent
   $to = "me@example.com";
   $subject = "Website Contact Form: ".$name;

   // build the message
   $message = "Name: ".$name."\n\n";
   $message .= "Email: ".$email."\n\n";
   $message .= "Message: ".$msg;

   // send it
   $mailSent =  mail($to, $subject, $message, $headers);

   // check if mail was sent successfully
   if (!$mailSent) {
   $errors['unknown_error'] = "Something went wrong...Please try again later";
   $data['success'] = false;
   $data['errors']  = $errors;
 }
 else {
   // show a message of success and provide a true success variable
   $data['success'] = true;
   $data['message'] = "Thank you for contacting me, I\'ll get back to you soon!";
 }
}

 // return all our data to an AJAX call
 echo json_encode($data);
?>

JS

 $(function() {
  $("#contactForm").submit(function(e) {
   $.ajax({
    type: 'POST',
    url: 'contact.php',
    data: $(this).serialize(),
    dataType: "json"
   })
   .done(function(msg) {
    if (msg.success == true) {
      response = '<div class="success">' + msg.message + '</div>';
      $contactform.hide();
    }
    else {
      response = '<div class="error">' + msg.errors + '</div>';
    }

    // Show response message.
    $("#contactForm").prepend(response);
  })
  e.preventDefault();
 });
});

答案 1 :(得分:0)

因为php成功返回结果。

如果php无法返回,将触发错误。

如果你希望你的Ajax处理程序做一些不同的事情,如果没有登录,要么在Ajax处理程序中指定(不推荐),要么在服务器端(在php中)执行,如果未经过身份验证,则返回你想要的内容。 / p>

$("#search_traveller_button").click(function(){
            $.ajax({
                url: "index.php?act=checkSessionUser",
                type: "POST",
                cache: false,
                success: function(data){
                    if (data==1){
                        console.log ("yeah it worked")
                    }else {
                        console.log ("error")
                    }
            });
        });