0

在下面的代码中,当我alert在调用 ajax 之前,它按预期执行并回显出正确的信息;但是,当我尝试通过 php 传递信息时,数据似乎是空的。我在我的 php 中做错了什么?

Javascript

$('#submit_fourth').click(function(){
    //send information to server   
    var email = $('input#email').val();
    var hash = $('input#username').val();
    var type = $('input#type').val();
    var finish = "email=" + email + "hash=" + hash + "type=" + type;

    alert(finish);
    $.ajax({
        cache: false,
        type: 'POST',
        url: 'process.php',
        data: finish,
        success: function(response) {
            alert('it worked!');
        }
    }); 
});

PHP

<?php
     $to      = 'blanet910@yahoo.com';
     $subject = 'Hash testing requested';
     $message = $_POST['finish'];
     $headers = 'From: webmaster@hashtester.com' . "\r\n" .
         'Reply-To: webmaster@hashtester.com' . "\r\n" .
         'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);
?>
4

2 回答 2

3

这是错误的:

var finish = "email=" + email + "hash=" + hash + "type=" + type;

至少应该是:

var finish = "email=" + email + "&hash=" + hash + "&type=" + type;

但是为了避免数据转义的问题(你没有这样做......),最好使用:

var finish = $("form").serialize();
于 2013-02-25T22:01:38.373 回答
1

您应该在普通对象中传递数据:

var email = $('input#email').val();
var hash = $('input#username').val();
var type = $('input#type').val();

$.ajax({
  cache: false,
  type: 'POST',
  url: 'process.php',
  data: {email: email, hash: hash, type: type},
  success: function(response) { alert('it worked!'); }
}); 
于 2013-02-25T22:04:09.780 回答