Javascript 为什么当我用AJAX中的POST向PHP发送数据时,它会说变量为null?

Javascript 为什么当我用AJAX中的POST向PHP发送数据时,它会说变量为null?,javascript,jquery,ajax,post,Javascript,Jquery,Ajax,Post,我有以下jQuery: $(document).ready(function() { $('input[type="submit"]').click(function() { event.preventDefault(); var email = $('.email').val(); $.ajax({ type: "POST", url: "register_email.php",

我有以下jQuery:

$(document).ready(function() {
    $('input[type="submit"]').click(function() {
        event.preventDefault();

        var email = $('.email').val();

        $.ajax({
            type: "POST",
            url: "register_email.php",
            data: JSON.stringify({ "email": email }),
            dataType: "json",
            contentType: "application/json",
            success: function(data) {
                alert(data);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                alert(textStatus + " " + errorThrown);
            }
        });
    });
});
email
变量已明确设置,我可以
提醒它

但是,当我进入PHP时,我的脚本如下:

<?php
    $db = new mysqli("localhost", "...", "...", "...");

    if ($db->connect_error) {
        echo "Could not connect to database.";
        exit;
    }
    else {
        $emerd = json_decode($_POST["email"]);

        $db->query("INSERT INTO emails (email) VALUES (' " . $emerd . "')");

        echo $emerd;
    }
?>

您没有将
json
字符串传递回JavaScript。你应该做:

echo json_encode(array(
   "email" => $emerd
));
除此之外,您不需要:

  • 在php中的
    $\u POST[“email”]
    上使用
    json\u decode
  • $.ajax
    请求中设置
    contentType
    选项或
    JSON.stringify
    数据对象

不要将其编码为数组,也不需要“email”周围的引号

 $.ajax({
        type: "POST",
        url: "register_email.php",
        data: { email: email, contact:$('#contact').val() }, //no problem even if you have more than one variables.
        success: function(data) {
            alert(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert(textStatus + " " + errorThrown);
        }
    });
在服务器端

$emerd = $_POST["email"];

将您的电子邮件字段放在如下表单中

<form id="myform"><input type="text" name="email"></form>

这是最好的方法,我认为这是推荐的方法。无需编码为JSON,然后在服务器端解码JSON。

您不需要
JSON.stringify({“email”:email}),
。。只要
{'email':email}
就足够了。你不需要php端的
json\u decode()
,请查看答案,了解一些处理方法。@DougSmith请记住,发布文章的方法不止一种。如果您真的需要发布JSON,那么您需要正确地将其字符串化,并在服务器上将其作为JSON处理。但是如果你有简单的数据,比如一个电子邮件地址,你可以把它作为传统的表单编码的键值对发布。观察您的原始请求(浏览器开发工具或Fiddler)以了解您的post值。类似于
email=abc%40example.com
的内容可能非常适合您的场景,因此您可以将JSON完全排除在请求之外,这样在PHP中阅读帖子就容易多了。@DougSmith URL编码的默认帖子将被称为如下内容:
jQuery.ajax({type:“post”,URL:“someurl”,数据:{email::abc@example.com"}}
-请注意,
数据
没有字符串化,您也没有给它一个JSON内容类型。这将产生post值,就像我在上一篇评论中所做的那样。这家伙说我需要引号并进行字符串化。使用FireBug\Chrome Developer工具检查您的XHR活动,看看有什么反应。@JeffNoel不,他没有需要使用
JSON.parse
,jQuery已经给了他一个解析过的对象。我得到“register\u email.php加载资源失败:服务器响应状态为500(内部服务器错误)”从控制台。这有什么意义?我可以直接访问它。附加更新的JS和PHP代码。确保PHP脚本中没有错误。
$('#myform").on('submit', function (e) {
    e.preventDefault();//this keeps the form submission from refreshing the page
   var data = $(this).serialize();
    $.ajax({
      url: '',
      data: data,  //assign the data like this
      type: "post",
      success: function (response){

      },
      ....other params 
   })
})